javascript 单击时在光标位置旁边创建一个 DIV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14032568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a DIV next to the cursor position on click
提问by George Ciobanu
What I'm trying to do is, when a user clicks somewhere on a page, a div containing a random image would show up on in the position of a click and it stays there. This must be able to be repeated, showing a different image every time. Any suggestions?
我想要做的是,当用户单击页面上的某个位置时,包含随机图像的 div 将显示在单击位置并停留在那里。这必须能够重复,每次显示不同的图像。有什么建议?
回答by Paul Fleming
JS:
JS:
$(function(){
var fadeDelay = 1000;
var fadeDuration = 1000;
$(document).click(function(e){
var div = $('<div class="image-wrapper">')
.css({
"left": e.pageX + 'px',
"top": e.pageY + 'px'
})
.append($('<img src="" alt="myimage" />'))
.appendTo(document.body);
setTimeout(function() {
div.addClass('fade-out');
setTimeout(function() { div.remove(); }, fadeDuration);
}, fadeDelay);
});
});
CSS:
CSS:
body {
position: relative;
}
.image-wrapper {
position: absolute;
transform: translate(-50%, -50%);
opacity: 1;
}
.image-wrapper.fade-out {
opacity: 0;
transition: opacity 1s ease-in-out;
}
回答by user1517081
With random images from 1 to 10:
使用从 1 到 10 的随机图像:
jQuery(document).ready(function(){
$(document).click(function(e){
var num = Math.floor((Math.random()*10)+1);
var img = $('<div>Image '+num+':<img src="image' + num + '.png" /></div>');
$("#img_container").html(img).offset({ top: e.pageY, left: e.pageX});
});
})