You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript字符串右旋转实现及H1文本长度获取异常求助

字符串右旋转练习中的文本获取与处理问题

正在进行JavaScript基础练习,其中第5题要求:

编写一个JavaScript程序,将字符串'w3resource'向右旋转。具体操作是定期将字符串末尾的一个字母移到开头。

我的思路是获取H1标签内的文本进行处理,知道JS字符串不可变,打算用新变量存储处理后的内容,但在获取H1文本时遇到问题:用childNodes[0].length得到的长度是47,且有效字符从索引20开始,排除了CSS的padding和margin影响,查了相关文档也没解决问题。

现有代码

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta name="Training">
        <meta name="author" content="Vitor Mota">
        <title>Training</title><!--Practice-->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">                       
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="cssFile2.css">
        <script src="JsExc2.js" defer></script>
    </head>
    <body >
        <div class="outer_content">
            <div class="rotate_content">
                <h1 class="rotate_h1_content">
                   Any string
                </h1>
                <h2 class="output">
                    
                </h2>
            </div>
        </div>
        
    </body>
</html>

CSS

body{
    background-color: black;
}

h1{
margin: 0px;
padding: 0px;

}
.rotate_h1_content, .rotate_content{
    margin: 0px;
    padding: 0px;
}
.outer_content{
    display: block;
    width: 100%;
    height: 200px;
    margin-top: 200px;
    margin-left: 0px;
    margin-right: 0px;
    padding: 1px;
    text-align: center;
    color: white;
}

JavaScript

let MyString = document.querySelector(".rotate_h1_content");

let output = document.querySelector(".output");

output.textContent = MyString.childNodes[0].length;

问题原因与解决方法

问题出在childNodes[0]获取的是包含大量换行、空格的文本节点——因为HTML中H1标签内的文本有缩进和换行,这些空白字符被算进了长度里。

1. 获取干净的文本内容

用textContent.trim()去除首尾空白字符,得到纯净的目标字符串:

const originalText = MyString.textContent.trim();
output.textContent = originalText.length; // 此时会得到正确的长度8

2. 实现字符串右旋转逻辑

写一个函数处理字符串右旋转,再通过定时器定期更新文本:

let MyString = document.querySelector(".rotate_h1_content");
let output = document.querySelector(".output");

// 获取干净的初始文本
let currentText = MyString.textContent.trim();
// 显示初始长度
output.textContent = currentText.length;

// 右旋转函数:把最后一个字符移到开头
function rotateRight(str) {
    if (str.length === 0) return str;
    return str.slice(-1) + str.slice(0, -1);
}

// 定期执行旋转,比如每1秒一次
setInterval(() => {
    currentText = rotateRight(currentText);
    MyString.textContent = currentText;
}, 1000);

这样就能正确获取文本长度,同时实现字符串定期右旋转的需求。

内容的提问来源于stack exchange,提问作者Sung-99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 04:15:17