2016-07-22 58 views
2

私はのコードを使用して9行のみのテキストエリアを作成し、このコードはjsfiddleで完全に動作します。https://jsfiddle.net/cityFoeS/3j48cpzn/ textareaはtextareaを9行に制限しませんに。コードはjsfiddleで動作しますが、htmlページでは動作しません

私の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

だからあなたは正確に何の問題が発生していますか?エラーメッセージ?奇妙な行動?それを明確にするために質問を編集する必要があります。 – Danieboy

+0

これは「」と「」タグにありますか? JSFiddleはこれを自動的に行いますが、あなた自身のHTMLページで自分で行う必要があります。 –

+0

@Danieboy今私はそれを入れました。私に通知してくれてありがとう –

答えて

0

問題がJSFiddleに、あなたがJavaScriptのオプションの下に "onloadイベント" に設定オプション "負荷タイプ" を持っているということです。あなたのコードで

は、しかし、JavaScriptは、これはエラーになります(これは、スタンドアロンのHTMLページとしてそれを実行しているときに私が得るものです)HTML —前に、すぐに実行します:

Uncaught TypeError: Cannot read property 'getAttribute' of null

あります<body>タグの最後に<script>タグを移動

  1. :2つのソリューション。たとえば、次の(jQueryを使って使用するために)window.onload関数や$(function() {})内のすべてのJavaScriptをカプセル化

    <body> 
        <!-- all your visible HTML elements --> 
        <script> 
         // all your JS code 
        </script> 
    </body> 
    
  2. 。たとえば、次のように

    <script> 
        window.onload = function() { 
         // all your JS code 
        }; 
    </script> 
    
関連する問題