javascript - 代码在 jsfiddle 中有效,但在 html 页面中无效

标签 javascript html css

<分区>

我正在使用来自 Max lines textarea 的代码创建一个只有 9 行的文本区域,这段代码在我的 jsfiddle 上完美运行,https://jsfiddle.net/cityFoeS/3j48cpzn/ textarea 不会像我希望的那样将 textarea 限制为 9 行。

我的 HTML:

<html>
<head>
<style>
body {
    background: black;
}
textarea {
    overflow: hidden;
    resize: none;
    font-family: courier;
    color: white;
    outline: none;
    line-height: 20px;
    margin: 0;
    padding: 0;
    border: 0;
    left: 45px;
    position: absolute;
    font-size: 14px;
    background-color: black;
    border-bottom: 1px solid white;
}
div {
    font-family: courier;
    color: white;
    line-height:20px;
    position: absolute;
    font-size: 14px;
    width: 29px;
    border-right: 1px solid white;
    border-bottom: 1px solid white;
    left: 10px;
}
</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
var limit = 9; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");

textarea.onkeyup = function() {
   var lines = textarea.value.split("\n");

   for (var i = 0; i < lines.length; i++) 
   {
         if (lines[i].length <= spaces) continue;
         var j = 0;

        var space = spaces;

    while (j++ <= spaces) 
    {
       if (lines[i].charAt(j) === " ") space = j;  
    }
    lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
    lines[i] = lines[i].substring(0, space);
  }
if(lines.length>limit)
{
    textarea.style.color = 'red';
    setTimeout(function(){
        textarea.style.color = '';
    },500);
}    
   textarea.value = lines.slice(0, limit).join("\n");
};
</script>
</head>
<body>
<div>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</div><textarea rows="10" cols="50" id="splitLines" onpaste="return false;"></textarea>
</body>
</html>

最佳答案

问题在于,在 JSFiddle 中,您在 JavaScript 选项下将“加载类型”选项设置为“onload”。

但是,在您的代码中,JavaScript 在 HTML 之前立即运行 — 这将导致错误(这是我在将其作为独立 HTML 页面运行时得到的结果):

Uncaught TypeError: Cannot read property 'getAttribute' of null

有两种解决方法:

  1. 移动 <script>标记到 <body> 的末尾标签。例如:

    <body>
        <!-- all your visible HTML elements -->
        <script>
            // all your JS code
        </script>
    </body>
    
  2. 将所有 JavaScript 封装在 window.onload 中功能或 $(function() {}) (与 jQuery 一起使用)。例如:

    <script>
        window.onload = function() {
            // all your JS code
        };
    </script>
    

关于javascript - 代码在 jsfiddle 中有效,但在 html 页面中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532166/

相关文章:

javascript - 显示随机 div javascript,有时只显示 div

javascript - 搜索字段在 Chrome 中不起作用

css - 如何为 Hgroup 子部分插入属性选择器

css - 调整页脚中的图像边距

javascript - 如何在 D3 v4 中只获取我需要的东西?

html - 如何为头像图像创建星形?

javascript - jQuery 使用 Ajax 用数据属性填充 div

css - 如何根据第 n 个位置添加*渐进式*动画延迟?

javascript - 如何使用 jquery 选择不是特定元素子元素的元素?

javascript - AngularJS:处理具有特定类的div的点击