[英]My button won't function on mobile but works fine on desktop?
昨晚我發表了一篇關於將文本和按鈕本身居中的帖子,並且我很高興收到大量解決該問題的反饋。 現在,我遇到了另一個問題,由於某種原因,按鈕無法在手機上運行嗎? 昨晚進行測試時,它運行良好,但現在當我嘗試將其應用到另一個頁面時,它在移動設備上無法正常工作。 該按鈕出現在移動設備上,但單擊后將不執行任何操作。 但是在台式機上卻沒有這樣的問題,所以我有點困惑。 我將在下面粘貼整個代碼。
看一下是否可以幫忙,
Thanks.`
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> #more {display: none;} </style> </head> <body> <span id="dots"></span><span id="more" style=color:black;>Example Text</span></p> <div style="text-align:center"> <button onclick="myFunction()" id="myBtn" style=color:white;background-color:black;>Lyrics</button></div> <script> function myFunction() { var dots = document.getElementById("dots"); var moreText = document.getElementById("more"); var btnText = document.getElementById("myBtn"); if (dots.style.display === "none") { dots.style.display = "inline"; btnText.innerHTML = "Lyrics"; moreText.style.display = "none"; } else { dots.style.display = "none"; btnText.innerHTML = "Read less"; moreText.style.display = "block"; moreText.style.textAlign = "center"; // btnText.parentElement.style.textAlign = "center"; } } </script> </body> </html>
`
您的HTML存在一些問題,下面將對它們進行評論:
<span id="dots"></span>
<!-- no quotes in the style attribute -->
<span id="more" style=color:black;>Example Text</span>
<!-- closing inexistent p tag -->
</p>
<div style="text-align:center">
<!-- no quotes in the style attribute -->
<button onclick="myFunction()" id="myBtn" style=color:white;background-color:black;>Lyrics</button>
</div>
修復以上所有問題后,我將提到使用onclick
是一個不好的做法 ,並且應將Element.addEventListener
與click
事件一起使用,如下所示:
var btn = document.getElementById("myBtn")
btn.addEventListener("click", myFunction)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.