javascript冲突或鼠标悬停事件过多



目前,我已经在背景图像上分层了4个图像。当鼠标悬停在每个图像上时,它会消失,直到用户刷新为止。我想创建一个图像的26个克隆。理想情况下,我可以定位每个图像副本,jquery会自动生成id名称,比如so(#myid(n((,也就是#myid1,#myid2。由于到目前为止我还无法完成图像克隆,我不得不一遍又一遍地复制和粘贴每一块代码。然而,一旦我添加了第六个映像,我就遇到了性能问题,我的代码就停止了工作。

我已经包括了两个代码笔。此代码笔可用于4个图像副本:https://codepen.io/narutofan389/collab/NWGpQWo

此代码笔不适用于6个副本:https://codepen.io/narutofan389/collab/MWapQyO

我听说过太多鼠标悬停事件会导致性能问题。我不确定这是否是我问题的根源。我也在尝试使用一个单独的代码笔来测试使用独立id的图像克隆。这是迄今为止从另一个堆栈溢出答案中提取的代码:

html

<body>
<div id="sand"></div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

javascript

$(document).ready(function(){
for (var i = 0; i < 2; i++) {  
var img = "<img src ='https://s3-us-west-2.amazonaws.com/s.cdpn.io/4405662/sandsmaller.png' 
id='myid"+i+"'/>"; 
$("body #sand").append(img);
}
})

我再次尝试生成不同的id,我可以单独定位?

由于您的克隆片段在jQuery中,我希望使用它的解决方案是可以接受的。

首先,我必须添加标记中缺少的#sand容器,因为它是代码附加图像的地方。此外,还为每个图像添加了一个div包装来镜像您的代码笔(尽管您可能不需要它(,并为图像添加了sand类。

然后,我没有为每个元素添加一个事件,而是使用了事件委派,这样我就可以只为包装元素附加一个处理程序。我的目标是#sand容器中尚未隐藏的所有图像。

然后稍微简化了css,删除了多余的规则,并将公共属性移动到新的类中。

for (let i = 1; i <= 6; i++) {
// Create the wrapping div
var $container = $("<div class='sand" + i + "'>");
// Create the img
var $img = $("<img src ='https://s3-us-west-2.amazonaws.com/s.cdpn.io/4405662/sandsmaller.png' class='sand' id='sand" + i + "'/>");
// Add image to container
$container.append($img);
// Add container to the document
$("body #sand").append($container);
}
// Listen when the mouse hovers an image
$('#sand').on('mouseenter', 'img.sand:not(.hide)', function() {
$(this).addClass('hide');
});
$('#sand').on('animationend', 'img.sand.hide', function() {
$(this).hide();
});
html {
background: url(https://i.postimg.cc/HWJvtDGx/lockcorrect.jpg) no-repeat center center fixed;
background-size: cover;
height: 100%;
overflow: hidden;
}
#bg {
position: fixed;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
#bg img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
}
@-webkit-keyframes fade {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@-moz-keyframes fade {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@-o-keyframes fade {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes fade {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.sand {
position: absolute;
height: 90vh;
}
#sand6 {
top: 0px;
right: 200px;
}
#sand5 {
top: 300px;
left: 500px;
}
#sand4 {
top: 300px;
right: 200px;
}
.hide {
animation: fade 3s;
animation-fill-mode: forwards;
}
#sand3 {
height: 100vh;
top: 0px;
left: 700px;
}
#sand2 {
height: 100vh;
top: 0px;
left: 300px;
}
#sand1 {
position: relative;
height: 100vh;
right: 30px;
}
<div id="bg">
<img src="https://i.postimg.cc/HWJvtDGx/lockcorrect.jpg
" alt="lock">
</div>
<div id="sand">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

最新更新