我是 jQuery 的新手,正在学习如何让它与我的实际代码交互,以便页面更具交互性,但我对所有功能有点困惑。我了解 jQuery 的原理,我觉得这很容易,但我真的不知道如何调用函数。现在我正在做一个测试页面来练习和习惯它。
我正在尝试完成我在购物网站上看到的 2 件事。
第一件事: 使文字出现在鼠标悬停图像上,如下所示 example
- 如您所见,当光标悬停在图像上时,会出现“快速查看”。这是我要做的第一件事。
第二件事: 单击图像时显示一个包含更多详细信息和信息的框,并在选择“关闭”时使出现的框消失(请使用前面的链接示例来查看我要实现的效果)。
因此,为了测试我的技能,我已经启动了这个测试代码来尝试完成我想要的。
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" > < /script>
<script>
$( img ).mouseenter( handlerIn ).mouseleave( handlerOut );
</script >
.img {
background-color: #f6f6f6;
width: 241px;
height: 341px;
}
<body>
<div class="img">an image
<div>
</body>
我知道这与 $( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );
有关,这是我尝试做的第一件事。
第二件事我知道它与 .toggle()
对我好一点,我是一个菜鸟,刚刚开始弄清楚如何开始使用 jQuery。
最佳答案
您可以使用 hover
函数:$( selector ).hover( handlerIn, handlerOut )
参见:http://api.jquery.com/hover/
// You want this code to run after the document has been loaded
jQuery(document).ready(function() {
// Use .img to target all elements with the class 'img'
$('.img').hover(function() {
// This function is called when the mouse hovers over the element
// Because this is function is an eventListener that is attached
// to an element, you can call 'this' to target the element
// that is being hovered over
var image = jQuery(this);
// Use the .append() function to insert content into an element
image.append("<div class='quick-view'>Quick view</div>")
},
function() {
// This function is called when the mouse leaves the element
// In here we want to remove the quick-view element, so
// first we have to find it. Again, use 'this' to
// target the element that is hovered over.
var image = jQuery(this);
// Use the .find() function to look for the quick-view element
// inside the element with the .img class:
var quick-view = image.find('.quick-view');
// Now to remove the quick-view element, use .remove()
quick-view.remove();
});
});
下面的代码会将 onClick 监听器附加到快速查看元素,以便您可以告诉您的脚本在单击快速查看元素时执行什么操作。
请注意我们没有使用
jQuery('.quick-view').click(function() {});
这是因为在加载文档后,这会将点击功能附加到所有具有“快速查看”类的元素。但是在加载文档后,没有具有“快速查看”类的元素。这些元素是动态创建的。因此,我们必须使用一个特殊的 jQuery 函数,即 .on() 函数,我们将把它附加到 body 元素上。参见 http://api.jquery.com/on/
jQuery('body').on('click', '.quick-view', function() {
// Even though the listerner seems to be attached to the body
// you can still call 'this' to target the quick-view element.
// In here you can add the box with more details to the body
jQuery('body').append("<div class='more-info'>more info</div>")
});
close 元素的功能可以用几乎相同的方式实现(始终对不是在加载时创建但动态创建的元素使用 .on())。
关于jquery - 如何使用 jQuery 创建悬停元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311382/