简体   繁体   中英

Adding a background gradient to existing background image with jquery

I am stuck with a problem that has me baffled for hours now. Here is the gist of it:

I have a div that has a background image already set and I want to add a background gradient with a background blend mode of multiply. This is so that when a person uploads a background image, it will automatically be rendered with the gradient above and no Photoshop is required to add it manually.

Right now I am at this point:

  • I get the current background image url and store it in a variable
  • I set the css with jquery to add that background image url and add a gradient (that is always the same)

Sounds simple enough, but it does not want to add my second gradient on that background.

Here is the code that I am currently using:

$( document ).ready(function() {
var bg = $(".dnd_area-row-4-background-image").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
$('.dnd_area-row-4-background-image').css('background-image', 'url(' + bg+ ')','linear-gradient', '(322deg, rgba(229,27,81,1) 0%, rgba(245,126,32,1) 100%);');
});

https://jsfiddle.net/qh028wf1/

Would greatly appreciate any help!

Working Demo: https://jsfiddle.net/yhde4xfa/

Your jquery of setting css background is wrong. The correct syntax should be;

$(document).ready(function() {
    var bg = $(".dnd_area-row-4-background-image").css("background-image")
    bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
    $('.dnd_area-row-4-background-image').css(
        'background-image', 
        'linear-gradient(322deg, rgba(229,27,81,1) 0%, rgba(245,126,32,1) 100%), url('+bg+')'
    );
});

Thank you @yeyene, good stuff that lead me to the actual solution that overrides any other styles. Posting below for posterity:

$(document).ready(function() {
    var bg = $(".dnd_area-row-4-background-image").css("background-image")
    bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
    $('.dnd_area-row-4-background-image').css(
        "cssText", "background-image: linear-gradient(322deg, rgba(229,27,81,1) 0%, rgba(245,126,32,1) 100%), url("+bg+")!important"
    );
  
});

This adds the css with the,important tag. which I am aware cannot be done through json like in the last version of this code. I appreciate your answer and the great community here for beginners!

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