如何在两个div之间切换
我试图在两个div之间切换。例如,onload,我希望显示左侧内容,并且正确的内容将保持隐藏状态。如果我单击右侧div,我希望隐藏左侧内容并显示正确的内容,反之亦然。我是javascript的新手,但这就是我所拥有的。我似乎无法让它发挥作用。请帮助...
I am trying to toggle between two divs. For example, onload, I want the left content to show and the right content will remain hidden. If I click the right div, I want the left content to hide and the right content to appear and vise versa. I am very new to javascript but here is what I have. I can't seem to get it to work. Please help...
这是我的HTML代码:
Here is my HTML code:
<div onclick="toggle_visibility('left');">
Left
</div>
<div onclick="toggle_visibility('right');">
Right
</div>
<div id="left" style="display: block;">
This is the content for the left side
<div>
<div id="right" style="display: none;">
This is the content for the ride side
</div>
这是我正在使用的Javascript:
Here is the Javascript I am using:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
现场演示 http://jsfiddle.net/PauWy/1/
HTML:
<p id="toggle">
<span> Left </span>
<span> Right </span>
</p>
<div id="left"> LEFT CONTENT </div>
<div id="right"> RIGHT CONTENT </div>
JavaScript:
JavaScript:
$('#toggle > span').click(function() {
var ix = $(this).index();
$('#left').toggle( ix === 0 );
$('#right').toggle( ix === 1 );
});
CSS(隐藏正确的DIV onload):
CSS (to hide the right DIV onload):
#right { display:none; }
将JavaScript代码放在页面底部。
<script>
$(function() {
// put jQuery code here
});
</script>
</body>
注意SCRIPT元素如何位于BODY元素的末尾。另外,请注意jQuery代码应该在ready处理程序中: $(function(){... code ...});
Notice how the SCRIPT element is located at the end of the BODY element. Also, notice that the jQuery code should be inside the ready handler: $(function() { ... code ... });