我意识到这可能是一个已经回答的问题,但我想问一下,如果市场上有新的东西可以轻松解决我的问题。
我正在使用 javascript 将图像加载到指定坐标。
var span = document.createElement("span");
span.innerHTML = "<img src=\"source.gif\" id=\"someid\">";
span.style.position = "absolute";
span.style.left = coodinatesLeft[i] + "px";
span.style.top = coodinatesTop[i] + "px";
document.body.appendChild(span);
稍后,当鼠标经过图像时,我想在 jquery 中使用简单的 mouseenter 函数
$("mydivid").mouseenter(function(){ $(this).text("something"); });
在图片所在的地方写一段文字。而且我没有得到任何文本,我想,因为图像比文本更前景。其他时候我用过它,而且它起作用了,但后来我只有一个 div,上面没有实际的图像源。
有没有办法保持结构并将文本附加到图像上?
PS:我阅读了有关 z-index 的信息,但不确定它是否正是我需要的,因为我没有为图像预定义的 css 类。
提前致谢!
最佳答案
对于动态添加的元素,您应该使用事件委托(delegate)
。
$('<span />')
.html('<img src="source.gif" class="myImages">')
.css({
'position': 'absolute',
'left': coodinatesLeft[i] + 'px',
'top': coodinatesTop[i] + 'px'
})
.appendTo('body');
$('.myImages').hover(function() {
$(this).append('<span id="myText">MY TEXT HERE</span>');
}, function() {
$('#myText').remove();
});
CSS:
#myText {
height: same as .myImages;
width: same as .myImages;
opacity: .5;
background: #ccc;
}
关于javascript - 通过动态添加的 img 查询 text(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30569548/