此脚本将创建一个新元素并为其提供正确的 ID,但不会加载到下面的 HTML/字符串中:
<script>
$(function () {
$("#test img").on("click", function (e) {
var titleEl = document.createElement("div");
var laptopImg = $("#test img");
var theText = "<p>this is a test</p>"
document.body.appendChild(titleEl);
titleEl.id = "img-title";
titleEl.html = theText;
titleEl.position = laptopImg.position;
});
});
</script>
<style>
#img-title {
color:black;
z-index:1;
}
#test img {
position: absolute;
transform: scale(1,1);
-moz-transition-duration: 2s;
}
#test img:hover {
transform: scale(.5,.5);
-moz-transition-duration: 2s;
}
#test img:active {
-moz-transform:skew(360);
-moz-transition-duration: 2s;
}
</style>
<div id="test">
<%= image_tag('test_2.jpg') %>
</div>
我尝试了各种函数,例如 .val .appendChild 等...但似乎都不起作用。每次我单击图像时,它只会创建一个新的空 div。
最佳答案
作为原始解决方案,您需要使用 innerHTML
$(function() {
$("#test img").on("click", function(e) {
var titleEl = document.createElement("div");
var laptopImg = $("#test img");
var theText = "<p>this is a test</p>"
document.body.appendChild(titleEl);
titleEl.id = "img-title";
titleEl.innerHTML = theText ;
titleEl.style.position = laptopImg.css('position');
});
});
演示:Fiddle
jQuery-ish 解决方案将
$(function () {
var $laptopImg = $("#test img").on("click", function (e) {
var theText = "<p>this is a test</p>"
$div = $('<div />', {
id: 'img-title',
position: $laptopImg.css('position'),
html: theText
}).appendTo('body')
});
});
演示:Fiddle
注意:如果完成多次点击,还需要确保没有重复的 ID
关于javascript - 为什么这个 Javascript 没有添加到 HTML 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18708751/