e
参数现在可以在下面的函数中使用,但如果在函数中定义了它,则可以使用。
这里是它的一个参数,并在底部调用:
function getRotVal( e ) {
var el = document.getElementById( e ), // e is a parameter in the function
st = window.getComputedStyle( el, null ),
tr = st.getPropertyValue( 'transform' ) || "FAIL",
values = tr.split('(')[1].split(')')[0].split(','),
a = values[0],
b = values[1],
c = values[2],
d = values[3],
scale = Math.sqrt(a*a + b*b),
sin = b/scale,
angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
return angle;
}
var box = document.getElementById( 'box' );
var result = getRotVal( box );
alert( result );
.box {
width: 5rem;
height: 5rem;
margin: 0.75rem auto;
background-color: #222;
transform: rotate( 15deg );
}
<div id="box" class="box">
</div>
在这里,我在函数中定义了变量:(它可以工作)
function getRotVal() {
var el = document.getElementById( 'box' ), // e is defined inside function
st = window.getComputedStyle( el, null ),
tr = st.getPropertyValue( 'transform' ) || "FAIL",
values = tr.split('(')[1].split(')')[0].split(','),
a = values[0],
b = values[1],
c = values[2],
d = values[3],
scale = Math.sqrt(a*a + b*b),
sin = b/scale,
angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
return angle;
}
var result = getRotVal();
alert( result );
.box {
width: 5rem;
height: 5rem;
margin: 0.75rem auto;
background-color: #222;
transform: rotate( 15deg );
}
<div id="box" class="box">
</div>
我希望此函数是动态的并接受不同的变量,因此第二个片段不是那么好。如何获得第一个代码片段,并将e保持为变量?
最佳答案
在第一个代码段中,您将DOM元素传递给getRotVal
函数,并且再次在DOM元素上使用了getElementById
。
因此,只需注释el的第一行,然后将函数参数e
直接传递给getComputedStyle,如下所示
// var el = document.getElementById( e ), // e is a parameter in the function
st = window.getComputedStyle(e, null),
程式码片段:
function getRotVal(e) {
// var el = document.getElementById( e ), // e is a parameter in the function
var st = window.getComputedStyle(e, null),
tr = st.getPropertyValue('transform') || "FAIL",
values = tr.split('(')[1].split(')')[0].split(','),
a = values[0],
b = values[1],
c = values[2],
d = values[3],
scale = Math.sqrt(a * a + b * b),
sin = b / scale,
angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
return angle;
}
var box = document.getElementById('box');
var result = getRotVal(box);
alert(result);
.box {
width: 5rem;
height: 5rem;
margin: 0.75rem auto;
background-color: #222;
transform: rotate( 15deg);
}
<div id="box" class="box">
</div>
关于javascript - 除非我在函数中定义变量,否则传递变量不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43692348/