开发者

jquery .find and .replace div background

Lets say I have two divs

How do I use .find to get div1's background image, than apply that background image to div2, and replace ".jpg" with "_highlighted.jpg" ?

var div2bg = $('.div1').find('div').attr('background-image'??)//how to assigned the background image as a variable?

$('.div2'开发者_开发知识库).css("background-image", "url(" + div2bg + ")");
$('.div2').css("background-image").replace(".jpg", "_highlighted.jpg");


Close but replace returns a string, it doesn't change the source.

I think you want this instead:

var div2bg = $('.div1').css('background-image');

$('.div2').css("background-image", div2bg.replace(".jpg", "_highlighted.jpg"));


You an accomplish this with the following code:

// Get the first background image
var bg = $(".div1").css("background-image");
// Assign a modified version to another DIV
$(".div2").css("background-image", bg.replace(".jpg", "_highlighted.jpg"));

Whether or not the following is applicable to your project, you decide: I would like to point out this type of stuff is generally best handled with classes, and using jQuery methods like:

$(".div2").addClass("highlighted");
$(".div2").removeClass("highlighted");

It greatly reduces the verbosity of your scripts, and allows you to keep visual styles maintained in your CSS, rather than being partially-dependent upon values and strings within scripts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜