是否可以获取现有的CSS规则属性,然后使用jQuery编辑它
我的旋转木马中有一个背景图像,我正试图使用jQuery为它添加一个渐变 以下是我试图编辑的元素的CCS代码:是否可以获取现有的CSS规则属性,然后使用jQuery编辑它,jquery,css,Jquery,Css,我的旋转木马中有一个背景图像,我正试图使用jQuery为它添加一个渐变 以下是我试图编辑的元素的CCS代码: element.style { padding: 5% 5%; margin: 0px 0%; background-image: url(myImgUrl); background-position: left top; background-size: contain; min-height: 427px; } 这就是它最后的样子(添加渐变后) 这是我试过的 jQuer
element.style {
padding: 5% 5%;
margin: 0px 0%;
background-image: url(myImgUrl);
background-position: left top;
background-size: contain;
min-height: 427px;
}
这就是它最后的样子(添加渐变后)
这是我试过的
jQuery(function(){
jQuery(".sa_hover_container").each(function){
var img = (this).css("background-image");
var newBackground = "linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1)), "+ img ;
(this).css(background-image,newBackground);
});
});
甚至可以这样做吗?如果是,我做错了什么
谢谢 您可以这样尝试:
jQuery(function(){
jQuery(".sa_hover_container").each(function){
var imgStyle = this.currentStyle || window.getComputedStyle(this, false),
var bgImage = imgStyle.backgroundImage.slice(4,-1);
var newBackground = "linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1)), " + bgImage;
jQuery(this).css(background-image,newBackground);
});
});
通过这种方式,即使在CSS文件中定义,也可以获得后台url。首先修复JS代码
jQuery(function(){
jQuery(".sa_hover_container").each(function() {
var img = jQuery(this).css("background-image");
var newBackground = "linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1)), "+ img;
jQuery(this).css("background-image",newBackground);
});
});
我有网址(img)[编辑]!,仍然不起作用。当提醒img时,您只会得到url。不是吗?你能发布一个提琴吗?一种方法是创建css类,并用类列表添加/删除它们。(但我认为这并不是最适合你的情况)首先,你需要在“背景图像”周围加上引号。我还是个新手,这完全解决了这个问题。亲爱的先生。(这个)->jQuery(这个),一些错误的括号,背景图片->背景图片。当您使用一些好的IDE(如PHPStorm)时,它会向您显示出问题所在。
jQuery(function(){
jQuery(".sa_hover_container").each(function() {
var img = jQuery(this).css("background-image");
var newBackground = "linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1)), "+ img;
jQuery(this).css("background-image",newBackground);
});
});