This script takes the .trg
class elements that are in the packaging element id="wrap"
. When you hold the mouse over some target elements it starts to run time (I have currently set 500ms). The time is set to the variable var delay = 500
. When this time expires, the script takes the data
attribute of the target element and creates a new element img. When you remove the mouse cursor from the target element, all elements with class .img
are removed... thus the created image is removed.
For site optimization, this method is better because you will not load content that is invisible... but you will create it when needed.
With small adjustments to my code, you can change it to add a class to an existing element or work in another way that works for you.
Example:
$(document).ready(function () {
var delay = 500; // <-- delay time in ms
var wrp = '#wrap';
var mouseMove;
var url;
var el;
var show = true;
$(wrp + ' .trg').on('mouseenter', function () {
mouseMove = new Date().getTime();
show = true;
el = this;
url = $(this).attr('data');
});
$(wrp + ' .trg').on('mouseout', function () {
$('.img').remove();
});
setInterval(function () {
var curTime = new Date().getTime();
if (curTime - mouseMove > delay && $(wrp + ':hover').length != 0 && show) {
var img = document.createElement('img');
img.setAttribute('class', 'img');
img.setAttribute('src', url);
el.append(img);
show = false;
}
}, delay);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="wrap">
<div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_027_by_54ka-165x165.jpg">Lorem 01</div>
<div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_005_by_54ka-165x165.jpg">Lorem 02</div>
<div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_006_by_54ka-165x165.jpg">Lorem 03</div>
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…