使用jQuery显示和隐藏div
问题描述:
当您点击链接时,它会显示divsomecontent。如果再次点击链接,它将隐藏。如何在悬停在链接上时进行div显示并在移开时隐藏而不是在点击时显示和隐藏?
When you click on the link, it with display the div "somecontent". And if you click on the link again, it will hide. How can I make the div show when hovering over the link and hide when moving away instead of showing and hiding on click?
以下是代码:
<script type="text/javascript">
$(document).ready(function(){
$(".showcontent").click(function(){
$(".somecontent").toggle("fast");
});
});
</script>
<a class="showcontent" href="">Show</a>
<div class="somecontent">
<p>some content</p>
</div>
答
只需替换/删除点击事件并添加鼠标悬停和mouseout(你可以链接原始元素选择)。
Just replace/remove the click event and add mouseover and mouseout (you can chain on the original element selection).
<script type="text/javascript">
$(document).ready(function(){
$(".showcontent").mouseover(function(){
$(".somecontent").show();
}).mouseout(function(){
$(".somecontent").hide();
});
$(".somecontent").mouseout(function() { $(this).hide(); });
$(".closelink").click(function() { $(this).parent().hide(); });
});
</script>
<a class="showcontent" href="">Show</a>
<div class="somecontent">
<p>some content</p>
</div>
编辑:根据Colin的建议..
With Colin's Suggestion..
对元素进行一点点重构,这应该能够提供你想要的结果。
A little refactoring of the elements, this should provide the results you want.
<div class="showcontent">
<a href="#">Show</a>
<div class="somecontent">
<span class="closelink">Close</span>
<p>some content<br />
<a href="#">Link 1</a><br />
<a href="#">Link 2</a><br />
<a href="#">Link 3</a>
</p>
</div>
</div>