我有一个有多个子div的父div。父div 在鼠标悬停时有一个悬停事件,它会显示 dom 上的一些文本。子div 也具有相同的功能。
我已经尝试过鼠标悬停/鼠标退出和鼠标离开等,但它们不太适合我的使用。
当您将鼠标悬停在父级上时,消息"foo"会在 dom 中显示当您将鼠标悬停在孩子身上时,消息"bar"会显示在 dom 中当您将鼠标悬停回父级而不离开父级时,不会显示任何消息。在这一点上,我希望它被重置为具有与最初相同的功能。
请问实现这一目标的最佳方法是什么?因为我不想重新排列 dom,因为它非常耗时
谢谢
这是一个猜测,但这(或类似的东西)可能会像你描述的那样做。
$(function(){
var disabled = false;
var theMessage = $("#theMessage");
$("#theParent").on("mouseover",function(e){
if(e.target.id == "theChild"){
theMessage.text("bar");
disabled=true;
} else if(!disabled) {
theMessage.text("foo");
}
}).on("mouseout",function(e){
if(e.target.id == "theParent"){
disabled=false;;
}
theMessage.text("...")
});
});
#theParent {width:200px; height:200px; background:red; position:relative;}
#theChild {position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; width:100px; height:100px; background:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="theMessage">...</div>
<div id="theParent">
<div id="theChild"></div>
</div>
v2:
$(function(){
var disabled = false;
var theMessage = $("#theMessage");
$("#theParent").on("mouseover",function(e){
if(e.target.id == "theChild"){
theMessage.text("bar");
} else {
theMessage.text("foo");
}
}).on("mouseout",function(e){
if(e.target.id == "theParent"){
disabled=false;
theMessage.text("...");
}
});
});
#theParent {width:200px; height:200px; background:red; position:relative;}
#theChild {position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; width:100px; height:100px; background:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="theMessage">...</div>
<div id="theParent">
<div id="theChild"></div>
</div>
v3:使用data-attribute
存储悬停文本:
$(function(){
var theMessage = $("#theMessage");
var defaultTxt = theMessage.text();
$("#theParent, #theChild").on("mouseover",function(e){
e.stopPropagation();
theMessage.text($(this).data("txt"));
});
$("#theParent").on("mouseout",function(){
theMessage.text(defaultTxt);
});
});
#theParent {width:200px; height:200px; background:red; position:relative;}
#theChild {position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; width:100px; height:100px; background:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="theMessage">...</div>
<div id="theParent" data-txt="foo">
<div id="theChild" data-txt="bar"></div>
</div>
http://jsfiddle.net/vnzunp5w/16/
e.preventDefault();
e.stopPropagation();
似乎是赢家!
我必须这样做才能最初隐藏箭头,而不是仅在悬停时显示它们。使用此滑块 http://www.idangero.us/swiper/#.Vk4so7erTRY(迄今为止我找到的最好的一个)
$('.swiper-button-next, .swiper-button-prev').addClass('hide');
var hoverArrows = function(){
console.log("hoverArrows")
$('.swiper-wrapper, .swiper-button-next, .swiper-button-prev').mouseenter(function () {
console.log("hovered")
$('.swiper-button-next, .swiper-button-prev').removeClass('hide');
}).mouseleave(function () {
$('.swiper-button-next, .swiper-button-prev').addClass('hide');
});
}
hoverArrows();