<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<style>
.matrix_box { width:150px; height:150px; background-color:#a0b3d6; }
</style>
<script src="js/jquery-3.3.1.js"></script>
<script>
(function() {
var $ = function(selector) {
return document.querySelector(selector);
};
var $css3Transform = function(element, value) {
var arrPriex = ["O", "Ms", "Moz", "Webkit", ""], length = arrPriex.length;
for (var i=0; i < length; i+=1) {
element.style[arrPriex[i] + "Transform"] = value;
}
};
if ($ && window.addEventListener) {
$("#matrixButton1").addEventListener("click", function() {
$css3Transform($("#matrixBox1"), "matrix(1,0,0,1,30,30)");
});
$("#matrixButton2").addEventListener("click", function() {
$css3Transform($("#matrixBox2"), "translate(30px,30px)");
});
} else {
alert("目前浏览器不支持CSS3 transform, 请试试其他浏览器");
}
})();
</script>
</head>
<body>
<div id="matrixBox1" class="matrix_box"></div>
<p><button id="matrixButton1" type="button">点击应用matrix(1,0,0,1,30,30)</button></p>
<div id="matrixBox2" class="matrix_box"></div>
<p><button id="matrixButton2" type="button">点击应用translate(30,30)</button></p>
</body>
</html>
js代码获取dom元素的时候,dom还没有渲染,需要在页面渲染之后再执行js语句,将js代码放在body后面就行了
这种情况类似于java空指针异常,换个方法,你给那两个按钮加两个onclick事件试一下。
function buttonClick()
{
$css3Transform($("#matrixBox1"), "matrix(1,0,0,1,30,30)");
}
if ($ && window.addEventListener)
{
buttonClick();
}
把这段js代码放在body的后面