如何使用女巫设置为百分比的jquery直接获取转换的css值

时间:2017-03-28 06:38:56

标签: javascript jquery html css

我设置了transform:translate(200%,700%);

当我尝试通过下面的代码阅读它时,我将此值作为px:

calculateAllowed = function (obj) {
        var matrix = $(obj).css('transform');
        alert(matrix);
        var values = matrix.match(/-?[\d\.]+/g);
        var x = values[4];
        alert(x);
};

x是整数

我希望得到200或“200%”。 我怎么能把它作为我第一次设定的百分比?

2 个答案:

答案 0 :(得分:1)

您需要将其除以宽度并将其乘以100以获得百分比形式。

function calculateAllowed(obj) { //just for easy testing
        var matrix = $(obj).css('transform');
        console.log(matrix);
        var values = matrix.match(/-?[\d\.]+/g);
        var x = values[4];
        var end = x / $(obj).width() * 100;
        console.log(end);
};

calculateAllowed( $("div") )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div style="transform: translate(200%, 700%)" >afwe</div>

答案 1 :(得分:1)

而不是

$(element).css('transform');

您可以使用:

如果使用javscript:

element.style.transform

使用Jquery:

$(element).style.transform

FIDDLE

使用Javascript的代码段

function myFunction() {
  var matrix = document.getElementById("myDIV").style.transform;
  alert(matrix);
  var values = matrix.match(/-?[\d\.]+/g);
  alert(values);
}
#myDIV {
  margin: auto;
  border: 1px solid black;
  width: 200px;
  height: 100px;
  background-color: coral;
  color: white;
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV" style="transform: translate(20%, 70%)">
  <h1>myDIV</h1>
</div>