此脚本将创建一个新元素并为其提供正确的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。
答案 0 :(得分:2)
作为原始解决方案,您需要使用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
答案 1 :(得分:0)
此代码段应为您添加div
$(function() {
$("#test img").on("click", function(e) {
var laptopImg = $("#test img");
$('<div id="img-title"><p>this is a test</p></div>')
.appendTo(document.body)
.css('position', 'absolute')
.offset(laptopImg.offset());
});
});