访问textNode.样式

Accessing textNode.style in DOM

本文关键字:样式 textNode 访问      更新时间:2023-09-26

对于html,我有一堆标签,看起来如下,我用它来生成清单。

<input type="checkbox"/> (some text here...)

我已经尝试了一些事情,试图通过使用javascript或css来尝试和样式化标签之外的文本,只有当复选框被选中时。和我得到一个关于"不能设置属性'未定义的textDecoration'的错误。当我记录。style的nextSibling,这是什么回来作为未定义的,但我能够从。nextSibling返回字符串。

这是我的javascript,我的日志检查=== true返回

"检查"

"相关复选框后面的文本"

经过第二个console.log的代码行抛出错误。

对于else块,控制台返回

" !检查"

下一行代码抛出同样的错误。

function main()
{
var checkBox = [];
var page;
page = document.getElementById("Content");
checkBox = page.childNodes;
for (i = 0, j = page.childNodes.length; i < j; i++)
{
if (checkBox[i].type == "checkbox")
{
    if (checkBox[i].checked === true)
    {
        console.log("checked");
        console.log(checkBox[i].nextSibling);
        checkBox[i].nextSibling.style.textDecoration = "line-through";
    }
    else
    {
        console.log("!checked");
        checkBox[i].nextSibling.style.textDecoration = "default";
    };
};
};
}; //main()

我已经测试了。nextsibling。样式,它返回为undefined…所以,我的问题是我如何定义它,或者我将不得不通过我的项目,并把所有我想样式的文本到标签?如果是这样,是否有可能通过javascript自动做到这一点?

这是我想出的css解决方案,但我不知道如何调用nextSibling,或者我甚至不知道是否可以。

input[type=checkbox]:checked + nextSibling
{
    text-decoration: line-through;
}

你想要的样式是不可能的,Text节点没有style属性:

你要做的是用一些东西包裹文本,我会使用<span>:

<input type="checkbox">
<span class="text>Some Text Here</span>

在你的JS中:

var texts = document.querySelectorAll('.text');
for(var i = 0, l = textNodes.length; i < l; i++) {
     if(texts[i].previousElementSibling.checked) {
       texts[i].style.textDecoration = 'line-through';
     } else {
       texts[i].style.textDecoration = 'Default';
     }
}

如果你使用我的库NodeList.js,你可以这样做:

$$('input:checked').nextElementSibling.style.set('textDecoration', 'line-through');

我找到了一个解决方案。我使用几个嵌套的if循环来测试childNode是文本节点还是html标记。如果它是一个文本节点,我将收集数据,并创建包含该数据的html标记。最后,我使用replaceNode()来插入更新后的代码。我相信有更好的选择,最终我将用标签替换所有的文本节点,并使用css,但这是目前工作。