简体   繁体   中英

How to add background-image and linear gradient Jquery?

I Want to add the below background-image css property, both link of the image and linear-gradient through JQuery . even just the link is not working for me

.product-video-container {
    background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("../Images/chicago.jpg");
}

my attempt is this :

$(document).ready(function () {

  $(".product-video-section .product-video-container").each(function () {
    var _self = this;
    $('.product-video-container',_self).css('background-image', './Images/chicago.jpg')
  });
})

This code:

$('.product-video-container', this).css...

is the equivalent of:

$(this).find('.product-video-container').css...

ie looks for .product-video-container as a descendent of this - as this is already a .product-video-container it would mean your html would need to be:

<div class='product-video-section'>
  <div class='product-video-container'>
    <div class='product-video-container'>
    </div>
  </div>
</div>

which seems unlikely.

Assuming you have:

<div class='product-video-section'>
  <div class='product-video-container'>
  </div>
</div>

Keeping the .each and _self which are used elsewhere in the app (unrelated code, but relevant for OP), you can use:

$(document).ready(function () {
  $(".product-video-section .product-video-container").each(function () {
    var _self = this;
    $(_self).css('background-image', '../Images/chicago.jpg')
  });
})

(also changed to path ../Images/ )

When using multiple backgrounds, keep in mind that they are treated as a stack. The first property will be on top, and the second will be underneath it. In your example, the gradient will appear on top, and the image will appear on the bottom. Here's how you can implement a stacked background using the CSS method in jQuery:

$(document).ready(function(){
    $(".background").css("background-image", "linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url("../Images/chicago.jpg");
});

Change ".background" to be your class or use (this).find(.class) for multiple classes.

$(document).ready(function () {

  $(".product-video-section .product-video-container").each(function () {

     $('.product-video-container').css('background-image', 'linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 1)), url("../Images/chicago.jpg")');
  });

  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM