在 javascript 中设置子字符串的样式 [英] Style a substring in javascript

查看:22
本文介绍了在 javascript 中设置子字符串的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 javascript 设置子字符串的样式.这是我的代码:

Hi i am trying to style a substring with javascript. Here's my code:

function runtest(){
    document.getElementById("test1").innerHTML.substring(0,2).style.fontStyle="italic";
}

substring 函数可以工作,但是当我添加样式时,错误控制台给我一个未定义"的错误.如何使用 javascript 设置此子字符串的样式?

The substring function works but when I add the style the error console gives me an error of "undefined." How can I style this substring with javascript?

推荐答案

两个选项:

  1. innerHTML 解决方案.警告:这将删除您正在执行的元素中任何元素上的任何事件处理程序.我主要在这里提到它,所以我可以指出这一点:

  1. An innerHTML solution. Warning: This will remove any event handlers on any elements within the element you're doing it on. I mention it here mostly so I can point that out:

var elm = document.getElementById("test1");
var html = elm.innerHTML;
elm.innerHTML = '<span style="font-style: italic">' + html.substring(0, 2) + '</span>' + html.substring(2);

  • 使用 splitText.在这里,我假设您要在 span 中换行的文本是元素中的 first 文本节点.这不会弄乱元素上的事件处理程序:

  • Using splitText. Here I'm assuming the text you want to wrap in a span is the first text node within the element. This won't mess up event handlers on the elements:

    var elm = document.getElementById("test1");
    var node = elm.firstChild;
    var span = document.createElement('span');
    node.splitText(2);
    span.style.fontStyle = "italic";
    elm.insertBefore(span, node);
    span.appendChild(node);
    

    splitText 创建两个相邻的文本节点,以前有一个,拆分点位于您指定的偏移处.然后我们取第一个并将其包装在 span 中.

    splitText creates two adjacent text nodes where there used to be one, with the split point being at the offset you specify. Then we take the first one and wrap it in a span.

    现场示例 |直播源

    这篇关于在 javascript 中设置子字符串的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆