【问题标题】:Why this code does not working properly on Firefox, Safari and Edge为什么此代码在 Firefox、Safari 和 Edge 上无法正常工作
【发布时间】:2017-06-20 14:11:50
【问题描述】:

两天前我问了一个关于堆栈溢出的问题。 How can I get all the properties from the class or id on click using jQuery?

我只想知道为什么这段代码在 Firefox、Safari 和 Edge 中不能正常工作,我该如何解决。

$(".sample").click(function() {
  var html = [],
    x = $(this).css([
      "margin", "padding", "color", "border"
    ]);

  $.each(x, function(prop, value) {
    html.push(prop + ": " + value);
  });

  $("#result").html(html.join("<br>"));


})

关于代码:

代码用于获取元素的css属性。

问题:

正如我上面所描述的,问题是由@wazz 报告的,谢谢。

请查看给定链接中的评论部分。

先谢谢了。

更新:这是我的完整代码

$(".sample").click(function() {
  var html = [],
    x = $(this).css([
      "margin", "padding", "color", "border"
    ]);

  $.each(x, function(prop, value) {
    html.push(prop + ": " + value);
  });

  $("#result").html(html.join("<br>"));


})
.sample {
  margin: 10px;
  color: #000;
  padding: 5px;
  border: 1px solid #4073ff;
}

#test {
  background: url(../sample.jpg) 20px 20px no-repeat cover red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button class="sample">Click</button>

【问题讨论】:

  • 我们应该检查哪个链接?
  • @CarstenLøvboAndersen 抱歉,我忘了提供链接。我已经编辑了我的问题
  • 请提供HTML,可能有几个原因。
  • @llya Kantor 当然可以。请稍等。
  • @llyaKantor 我已经更新了我的问题

标签: javascript jquery css firefox safari


【解决方案1】:
var elem1 = document.getElementById("elemId");
var style = window.getComputedStyle(elem1, null);
var keys = Object.keys(style); // will give margin,padding,color etc as keys  
var marginRight = style.margin-right;

这将为您提供一个以键为属性名称的样式对象。像魅力一样在 Firefox 中工作

【讨论】:

  • 对不起,它不能炒锅。
【解决方案2】:

它应该可以工作,与浏览器无关。我想问题可能如下: 1. $(".sample") 选择器可能返回多个对象。 2. 还要检查 $(this) 是否为您提供了您想要的确切 DOM?

【讨论】:

  • safari和firefox的问题是margin、padding、border除了颜色都是空的
  • 如果它应该列出如下,它对我有用: margin: 10px padding: 5px color: rgb(0, 0, 0) border: 1px solid rgb(64, 115, 255)
  • 我在 Windows 的 firefox (55.0b2) 和 safari ( 5.1.7 ) 中遇到问题,我遇到了问题但无法解决问题是它没有从每个函数,当我检查元素时,它在 Firefox 和 Safari 中显示 NaN
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 2016-09-15
  • 1970-01-01
  • 2016-03-27
  • 2015-07-04
  • 2017-09-05
  • 2012-09-10
  • 1970-01-01
相关资源
最近更新 更多