gpt4 book ai didi

javascript - HammerJS 中手势的简单示例

转载 作者:行者123 更新时间:2023-12-03 10:24:10 24 4
gpt4 key购买 nike

我正在尝试运行简单的手势代码,例如在浏览器上点击滑动

<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>

我正在尝试执行此代码,但显示错误无法读取 null 的属性“addEventListener”

最佳答案

正如所写,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>

关于javascript - HammerJS 中手势的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29484146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com