Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.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,我正在尝试加载图像作为父元素的背景。我已经成功了,但问题是我有几个具有不同背景的html部分 有没有一种方法可以用更少的编码或者其他方法来实现呢 我的代码: var imgFileData1 = $('.bg-img1').attr('src') $('#intro').css({'background-image':'url(' + imgFileData1 + ')'}); $('#bg-img1').hide(); var imgFileData2 = $('#bg-im

我正在尝试加载图像作为父元素的背景。我已经成功了,但问题是我有几个具有不同背景的html部分

有没有一种方法可以用更少的编码或者其他方法来实现呢

我的代码:

  var imgFileData1 = $('.bg-img1').attr('src')
  $('#intro').css({'background-image':'url(' + imgFileData1 + ')'});
  $('#bg-img1').hide();

  var imgFileData2 = $('#bg-img2').attr('src')
  $('#home').css({'background-image':'url(' + imgFileData2 + ')'});
  $('#bg-img2').hide();
我的html如下所示:

<section id="intro"><img id="bg-img1" src="intro.jpg"></section>
<section id="home"><img id="bg-img2" src="intro.jpg"></section>

为您的
标记分配一些

这使得使用jQuery进行选择更加容易

e、 g

HTML


听起来您可能想要创建一个可以使用的通用函数。例如,您可以使用类“标记”您的
img
元素。。。例如:

$(".load-image").each(function() {
  var self = $(this), img = self.find(".background-image");
  self.css("background-image", "url(" + img.attr("src") + ")");
  img.hide();
});
现在,您有了需要将其图像移动到其父对象背景中的图像列表。在此基础上,您可以使用与以下类似的逻辑:


完美的非常感谢!:)我错过了什么?为什么不把一些css规则和0行JS代码放在一起呢?
$(".load-image").each(function() {
  var self = $(this), img = self.find(".background-image");
  self.css("background-image", "url(" + img.attr("src") + ")");
  img.hide();
});
<img class='moveToParent' ...>
$(".moveToParent")
$(".moveToParent").each(i, element) {
    var imgData = $(this).attr("src");
    // Now apply the image to the parent.
});