我正在尝试运行简单的手势代码,例如在我的浏览器上点击滑动
<html>
<head>
</script src="https://hammerjs.github.io/dist/hammer.js">
</script>
<script>
var myElement = document.getElementById('myElement');
// create a simple instance
// by default, it only adds horizontal recognizers
var mc = new Hammer(myElement);
// listen to events...
mc.on("panleft panright tap press", function(ev) {
myElement.textContent = ev.type + " gesture detected.";
});
</script>
<style type="text/css">
#myElement {
background: black;
height: 300px;
text-align: center;
font: 30px/300px Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<div id="myElement"></div>
</body>
</html>
我正在尝试执行此代码,但这显示错误 无法读取属性&#39; addEventListener&#39;为null
答案 0 :(得分:1)
正如所写,javascript在DOM准备好之前运行,它将找不到要附加的元素。试试这个:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var myElement = document.getElementById('myElement');
// create a simple instance
// by default, it only adds horizontal recognizers
var mc = new Hammer(myElement);
// listen to events...
mc.on("panleft panright tap press", function(ev) {
myElement.textContent = ev.type + " gesture detected.";
});
});
</script>
您可以参考https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
文字的默认颜色为黑色,因此除非您通过添加color: white;
之类的内容来调整css,否则您将无法阅读该消息。
<style type="text/css">
#myElement {
background: black;
height: 300px;
text-align: center;
font: 30px/300px Helvetica, Arial, sans-serif;
color: white;
}
</style>