javascript - 我想通过单击跨度来循环显示纯文本下划线和换行
问题描述
如上所述,我希望在单击跨度时让 JS 在 textDecoration 中循环。我在另一个我找不到的答案中找到了这个片段,并(试图)修改它。
HTML
<div id="container">
<span>A</span> <span>B</span> <span>C</span> <span>D</span>
</div>
JS
var container = document.getElementById("container");
if (container.addEventListener) {
container.addEventListener('click', clickHandler, false);
}
else if (container.attachEvent) {
container.attachEvent('onclick', function(e) {
return clickHandler.call(container, e || window.event);
});
}
function clickHandler(event) {
var span = event.target;
if (span.style.textDecoration == 'none') {
span.style.textDecoration = 'underline'
}
else if (span.style.textDecoration == 'underline') {
span.style.textDecoration = 'line-through'
}
else if (span.style.textDecoration == 'line-through') {
span.style.textDecoration = 'none'
}
}
我认为问题在于使用 span 作为对象,但我不确定如何更正确地做到这一点。
解决方案
原因是这样的:
Element.style 返回 HTML 文档中使用的内联样式,由于样式不是直接在 HTML 中设置的,因此您将得到一个空值
所以,我一开始就把它设置为无。然后它将起作用。 看看这个看看为什么
var container = document.getElementById("container");
var spans = document.querySelectorAll('span')
for (let i = 0; i < spans.length; i++) {
spans[i].style.textDecoration = "none" // setting default
}
container.addEventListener('click', function(e) {
clickHandler(e)
});
function clickHandler(event) {
var span = event.target;
if (span.style.textDecoration == 'none') {
span.style.textDecoration = 'underline'
}
else if (span.style.textDecoration == 'underline') {
span.style.textDecoration = 'line-through'
}
else if (span.style.textDecoration == 'line-through') {
span.style.textDecoration = 'none'
}
}
<div id="container">
<span>A</span><span>B</span><span>C</span><span>D</span>
</div>
推荐阅读
- sql - 需要在 SQL 表中找到 Max 值并根据 MAX 值生成 Id
- asp.net - 如何获取要在 aspx 中使用的 jquery 数据表列的总和?
- flutter - dart gRPC:函数的含义是什么?
- c# - XML 验证成功但应该失败
- javascript - 在 Safari 浏览器上键入 Date Angular
- jquery - 使用放大镜图标触发搜索
- python-3.x - Matplotlib- 在多色线子图下方添加一个颜色条,如图所示
- javascript - 如何在 Promise.all 中使用第一个 promise 的结果,以此类推
- python - 如何在python中的等高线图上绘制梯度向量
- docker - 在 Dockerfile 中链接 docker 容器