首页 > 解决方案 > 我想通过单击跨度来循环显示纯文本下划线和换行

问题描述

如上所述,我希望在单击跨度时让 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 作为对象,但我不确定如何更正确地做到这一点。

标签: javascriptdomclick

解决方案


原因是这样的:

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>


推荐阅读