3

テキストエリアには、次の行があります。

hello world. <h2>sub heading</h2>
<img src="" alt="image.jpg"><h3>Test</h3>
More text
<img src="" alt="">

空の alt 属性にカーソルを移動するボタンをクリックできるようにしたいです。「h」タグがある場合、それらは適切な順序になっていますか (最初に h1 タグがあり、次に h2 タグがあるはずです)。順序が正しくない場合は、カーソルを次の "h" タグに移動します (この例では、カーソルを h2 タグに移動します)。最後に、カーソルは最後の alt 属性に移動します。ボタンをもう一度クリックすると、カーソルが「h2」タグに再び移動します。私は次のコードを持っています、

<script type = "text/javascript">            
      (function ($, undefined) {
 $.fn.getCursorPosition = function() {
    var el = $(this).get(0);
    var pos = 0;
    if('selectionStart' in el) {
        pos = el.selectionStart;
    } else if('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    return pos;
  }
})(jQuery);

function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
 else if(input.createTextRange){
 var range = elt.createTextRange();
 range.move('character', pos);
  range.select(); 
 }
 }

 function setCaretToPos (input, pos) {
 setSelectionRange(input, pos, pos);
 }

 function nextAlt(input) {
 var current = input.getCursorPosition();
 var search = input.val().substr( ( 0 == current ? 0 : current + 1 ) );
 var pos = current + search.search(/<[a-zA-Z]+(>|.*?[^?]>)/) + 1;
 if (-1 == pos) {
    alert("No elements found");
 } else {
    setCaretToPos(input.get(0), pos);
 }
 }
    </script>

テキストエリアとボタン内のテキスト:

 <textarea id="textarea">
 hello world. <h2>sub heading</h2>
 <img src="" alt="image.jpg"><h3>Test</h3>
 More text
 <img src="" alt="">
 </textarea>
 <br>
 <a onclick="nextAlt($('#textarea'));">Next</a>

上記のコードは IE では機能しません (クロス ブラウザーである必要があります)。カーソルを別のタグに移動しますが、カーソルを特定の場所に配置する前に別の条件を使用したいです。例えば、見出しタグの順番を確認したい。h2 と h3 が使用されている場合は、h1 タグをチェックし、カーソルを h2 タグに移動する必要があります。次に、ユーザーがボタンをもう一度クリックすると、見出しタグの順序は h2 の後で問題ないため、h3 タグではなく alt="" 属性 (代替テキストがない) に移動します。ユーザーがボタンをもう一度クリックすると、最後に到達すると、カーソルは再び「h2」タグに戻ります。誰かが私を助けてくれませんか。ありがとう

4

0 に答える 0