我想要改变这个编码器小提琴,以便不使用在DOM中找到的图像进行克隆,而是使用来自指定URL的图像,例如:http://graphics.cars.com/images/core/buying-guide-suv.png(来自background-url的图像)克隆: http://codepen.io/ElmahdiMahmoud/pen/tEeDn
如何使用jQuery从图像URL创建对象?
我尝试过这种方式,但它不能与上述小提琴一起使用:
var imgtodrag = document.createElement('img');
imgtodrag.src = "http://graphics.cars.com/images/core/buying-guide-suv.png";
实际尝试的代码:
var cart = $('#navigation .cart');
var imgtodrag_actual = $(this).parents('.search-result').find(".main-thumb .the-thumb"); //This is where the animation starts from
var imgtodrag_img = imgtodrag_actual.css("background-image"); // it is NOT an image element but a div with a background image - this is where the complication comes from
imgtodrag_img = imgtodrag_img.replace('url("','').replace('")',''); //the URL of that background image
var imgtodrag = document.createElement('img'); //now we need to create an object that will be cloned
imgtodrag.src = imgtodrag_img; //Set the image source of object, taken from the background image above
if (imgtodrag) {
var imgclone = imgtodrag.clone()
.offset({
top: imgtodrag_actual.offset().top,
left: imgtodrag_actual.offset().left
})
.css({
'opacity': '0.5',
'position': 'absolute',
'height': '150px',
'width': '150px',
'z-index': '100'
}) ......
我真的希望这是有道理的。
基本上,我想要使用小提琴代码,但小提琴中的图像来自一个元素。我需要它来自元素的背景图像。
答案 0 :(得分:2)
问题是imgtodrag
是一个dom元素,它没有像offset
这样的方法。此外,由于您正在创建img
的新实例,因此无需克隆它
在您的情况下,您可以使用jQuery创建新的img
元素
var imgtodrag = $('<img />', {
src: imgtodrag_img //Set the image source of object, taken from the background image above
}) //now we need to create an object that will be cloned
var imgclone = imgtodrag.offset({
top: imgtodrag_actual.offset().top,
left: imgtodrag_actual.offset().left
}).css({
'opacity': '0.5',
'position': 'absolute',
'height': '150px',
'width': '150px',
'z-index': '100'
})
答案 1 :(得分:1)
不是克隆现有图像,而是创建自己的图像对象。然后应用正确的源并继续使用codepen逻辑。
$('<img>').attr('src', src_for_image)
// continue with the code pen
这是一个更新的代码集:http://codepen.io/anon/pen/ogJRvj