我想使用javascript或jquery更改触摸屏设备上的数据属性。 “向下滚动以获取更多信息”的文字应该在触摸屏设备上说“触摸箭头”。触摸屏浏览器检测工作,我只是无法更改data-info属性。
以下是我的尝试:
HTML
<button class="trigger" id="trigger" data-info='Scroll down for more information'><span>Trigger</span></button>
JAVASCRIPT
<script>
if ('ontouchstart' in window)
{
// 'Getting' data-attributes using getAttribute
var trigger = document.getElementById('trigger');
var touchText = trigger.getAttribute('data-info');
// 'Setting' data-attributes using setAttribute
trigger.setAttribute('data-info','Touch the arrow');
}
</script>
CSS(如果重要的话)
button.trigger::before {
position: absolute;
bottom: 100%;
left: -100%;
padding: 0.8em;
width: 300%;
color: #fff;
content: attr(data-info);
font-size: 0.35em;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
非常感谢你的帮助!!
答案 0 :(得分:4)
如图所示更新属性的代码是正确的(example)。如果它无法正常工作,最可能的解释是,您的script
元素在之前是标记中的button
元素。在这种情况下,按钮在代码运行时不会存在,因此元素不会被更新。在标记中的button
之后确保脚本为。
答案 1 :(得分:1)
您的代码应该通过setAttribute
运行,但是在Javascript中,如果您愿意,也可以使用HTMLElement.dataset:
var trigger = document.getElementById('trigger');
trigger.dataset.info = "Scroll down for more information";
根据T.J.克劳德说,你的问题可能与你的脚本相对于你的“触发器”的位置有关。将您的脚本移动到body
的末尾,或使用某种onload
事件(但是,将脚本移动到身体末端是许多人的首选方法):
window.onload = function() {
// your code here
}