Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jQuery设置背景图像_Jquery_Html - Fatal编程技术网

使用jQuery设置背景图像

使用jQuery设置背景图像,jquery,html,Jquery,Html,我正在使用的图像响应。一个要求是内部图像必须设置为背景图像 我使用jQuery获取图像URL并将其设置为背景图像。然后我删除srcset,使它们不再是图像,而是成为背景图像 问题:不知何故,url值在inspector中显示的“urlmyBG”中没有显示。请看看我的JS,帮我一把 谢谢 JS HTML 这是因为你把myBG作为字符串传递进来。它应该是这样的:“url”+myBG+ $'source'。每个函数{ var myBG=$this.attr'srcset'; console.logm

我正在使用的图像响应。一个要求是内部图像必须设置为背景图像

我使用jQuery获取图像URL并将其设置为背景图像。然后我删除srcset,使它们不再是图像,而是成为背景图像

问题:不知何故,url值在inspector中显示的“urlmyBG”中没有显示。请看看我的JS,帮我一把

谢谢

JS

HTML


这是因为你把myBG作为字符串传递进来。它应该是这样的:“url”+myBG+

$'source'。每个函数{ var myBG=$this.attr'srcset'; console.logmyBG; $this.css'background-image','url'+myBG+; $this.removeAttr'srcset'; };
为了清晰,请考虑编辑你的文章,很难理解。
$('source').each(function() {
    var myBG = $(this).attr('srcset');
  console.log(myBG);
$(this).css('background-image', 'url(myBG)');
$(this).removeAttr('srcset');
})
<div>
<picture>
  <source media="(min-width: 768px)" srcset="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
  <source media="(min-width: 414px)" srcset="https://www.w3schools.com/tags/img_white_flower.jpg">
  <img src="https://www.w3schools.com/tags/img_pink_flowers.jpg">
</picture>
</div>