代码在jsfiddle中工作,但在html页面中不起作用

时间:2016-07-22 17:25:23

标签: javascript html css

我正在使用Max lines textarea中的代码创建一个只有9行的textarea,这段代码完全适用于我的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>

1 个答案:

答案 0 :(得分:0)

问题是在JSFiddle中,您可以选择&#34;加载类型&#34;设置为&#34; onload&#34;在JavaScript选项下。

然而,在您的代码中,JavaScript会在HTML之前立即运行 - 这将导致错误(这是我作为独立HTML页面运行时获得的结果):

  

未捕获的TypeError:无法读取属性&#39; getAttribute&#39;为null

有两种解决方案:

  1. <script>代码移至<body>代码的末尾。例如:

    <body>
        <!-- all your visible HTML elements -->
        <script>
            // all your JS code
        </script>
    </body>
    
  2. window.onload函数或$(function() {})中封装所有JavaScript(用于jQuery)。例如:

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