【问题标题】:Changing background property through jQuery is causing trouble in Safari通过 jQuery 更改背景属性在 Safari 中引起问题
【发布时间】:2017-01-27 10:07:26
【问题描述】:

Safari 的行为方式真的很奇怪,我不知道为什么它会添加额外的属性,从而在我正在处理的项目中给我带来很多麻烦。

测试很简单,这里有一个小技巧:

function clickme() {
	$('.container').css('background', "red");
}
.container {
  width: 100px;
  height: 100px;
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button onclick="clickme();">Click me!</button>

你会看到在 Chrome 或 Firefox 中,它会像你期望的那样添加 background: red,现在在 Safari 中添加这个:

style="background-color: red; background-position: initial initial; background-repeat: initial initial;"

这给我带来了麻烦,因为不允许我覆盖 background-image 的预定义 CSS 样式,我需要设置 background: '#color' 强制。否则 background-image 将始终在 background-color 之上,即使它在元素中是内联的。 Safari 现在不是我的朋友。

有什么解决办法吗?我会很感激的。

提前致谢。

【问题讨论】:

标签: javascript jquery css safari


【解决方案1】:

使用速记 background 属性内联似乎是一个问题。尝试将速记 background 属性分离为其各个属性:

$('.container').css('background-color', 'red');

或者您可以尝试使用带有 background 属性的类:

.bg {
    background: red
}

$('.container').addClass('bg');

【讨论】:

  • 问题是我需要它是“背景:红色”,就像在 Chrome 或 Firefox 中一样:/ 它看起来像 Safari 中的一个错误,对吧?现在,它只在使用 jQuery 时发生,因为如果你使用 setAttribute 使用平面 Javascript,它就不会发生......所以这是 jQuery 的错。
  • 我也不能这样做,它需要是内联样式的。感谢您尝试提供帮助。
  • @msqar 内联样式似乎不支持它。希望您找到解决方法:)
  • 是的,现在我只需要在 Safari 的内联样式中添加“background-image: none”,但我不知道,我还不相信用这种方法来修复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
相关资源
最近更新 更多