将背景图像从一个div复制到另一个div

时间:2017-03-11 20:12:12

标签: jquery css

我有多个div可以被视为具有不同background-image和css文件的按钮,其样式如下:

#button1 { background-image: url('../images/abc.png) }
#button2 { background-image: url('../images/def.png) }
#button3 { background-image: url('../images/ghi.png) }

每个按钮也是班级.button的一部分。

我还有一个带有“popup”类的div。如果我单击任何按钮,它会添加新类:isActive。

我想阅读具有“isActive”类的按钮的背景图像并将其放到“弹出”div中。

我想用jQuery做这样的事情:

var bg;
bg = $('.isActive').css('background-image')
console.log(bg)
$('.popup').css('background-image', bg )

不幸的是,console.log返回包含以下内容的bg:

  

文件:/// C:/Users/me/projects/images/abc.png

是否有一种优雅的方式来复制不完整的路径与“file://”等等,只是“../images/abc.png”,正如我在css中定义的那样?

3 个答案:

答案 0 :(得分:0)

为每个背景添加一个css类。然后你就可以分配弹出窗口你想要的任何背景。

library(dplyr)
data <- data %>%
  group_by(x) %>%
  mutate(
    width = 0.1 * n()
  )

pos <- position_dodge(width = 0.2)
myplot <-
  ggplot(data,
         aes(
           x = x,
           y = y,
           colour = treatment,
           width = width
         )) +
  geom_line(size = 1, position = pos) +
  geom_point(size = 3, shape = 16, position = pos) +
  geom_errorbar(aes(ymin = y - se, ymax = y + se), position = pos)

myplot

然后分配:

.bgr1 { background-image: url('../images/abc.png) }
.bgr2 { background-image: url('../images/def.png) }
.bgr3 { background-image: url('../images/ghi.png) }

更新

取自此处:Copy background from one element to another using jQuery not working in firefox

var allClasses = ['bgr1', 'bgr2', 'bgr3'];
var bgr = $('.isActive').attr('class').split(' ').filter(cls=>allClasses.indexOf(cls) > -1).shift();
if (bgr)
    $('.popup').addClass(ngr);

答案 1 :(得分:0)

您可以在此处找到您的解决方案:Get BackgroundImage

$(this).css('background-image');

答案 2 :(得分:0)

提示:您的js代码src(source)是相对于您的html / php文件而不是您的js文件。