从img标签获取背景图片网址,并使用该网址创建新的img标签 [英] get background image url from img tag and create new img tag with that url

查看:121
本文介绍了从img标签获取背景图片网址,并使用该网址创建新的img标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个

<div class="data">
<img src="#" style="background:url('o.jpg')">
</div>

我要使用此(背景)URL并在同一div中使用src ="background img url"创建新的img标签,并使用js或jq删除旧的img标签

i want to take this(background) url and create new img tag with src="background img url" in the same div and delete the old img tag using js or jq

我尝试从

var img = document.querySelector('img'),
    // parse image URL and strip away url('')
    imgURL = img.style.backgroundImage.replace('url("','').replace('")','');
img.src = imgURL;

// remove style attribute afterwards.
img.removeAttribute('style');

但是它对我不起作用,所以我必须换一种方式

but it is not working for me so i have to do it the other way

推荐答案

尝试这个

var img = $('#img').css('background-image');;
	
	imgURL = img.replace('url("','').replace('")','');
	img = imgURL;
	
	$('.data').html('<img src='+img+' width="100" height="100">');	

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="data">
<img src="#" style="background:url('o.jpg')" width="100" height="100" id="img">
</div>

这篇关于从img标签获取背景图片网址,并使用该网址创建新的img标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆