2016-12-02 2 views
0

の終了後にカーソルを表示させるタグの範囲を特定するためのすべてのソリューションは、あなたがhttps://jsfiddle.net/s7fxy8jp/8/ちょうどすべて<a>タグ

をチェックしてもらえあり、私はフォーカスを設定」をクリックしたときになるように、タグの範囲を識別するための任意の解決策はありますTo Z Element "をクリックすると、すべてのタグの終わりの直後にカーソルが表示されます。表示されるカーソルの場合

HTML

<div tabindex="-1" id="scripted"><a>Element A (script-only focusable)</a><a>Element B (script-only focusable)</a></div><div id="test">Set Focus To Element Z</div> 

CSS

div:focus { 
background-color: Aqua;} 

JS

document.getElementById('test').onclick = function() { 
document.getElementById('scripted').focus();}; 
+0

それは何を意味? : 'カーソルはすべてのタグの終わりの直後に表示されます。' – Jigar7521

+0

つまり、そのタグの最後にカーソルを移動したいのですか? – Jigar7521

答えて

0

、私はdivcontentEditableでなければならないと考えています。属性onClickを変更して、スクリプトが有効にした後にのみ編集可能にすることができます。

編集可能になると、set the selectionを使用してカーソル位置を配置できます。

function cursorToEnd(el) { 
    var range = document.createRange(); 
    var sel = window.getSelection(); 
    // Note positioning after the last child works for your 
    // example but might not be the most robust option depending 
    // on your expected div contents. 
    range.setStartAfter(el.lastChild); 
    range.collapse(true); 
    sel.removeAllRanges(); 
    sel.addRange(range); 
} 

document.getElementById('test').onclick = function() { 
    var e = document.getElementById('scripted'); 
    e.contentEditable = true; 
    cursorToEnd(e); 
}; 

jsFiddle

0

ここでは、これはですが、私は、テキストボックスにそのdiv要素を変換しておりませんので、あなたが最後にカーソルを表示することはできません。

document.getElementById('test').onclick = function() { 
 
    document.getElementById('scripted').focus(); 
 
    placeCaretAtEnd(document.getElementById("scripted")); 
 
}; 
 

 
function placeCaretAtEnd(el) { 
 
    el.focus(); 
 
    if (typeof window.getSelection != "undefined" 
 
      && typeof document.createRange != "undefined") { 
 
     var range = document.createRange(); 
 
     range.selectNodeContents(el); 
 
     range.collapse(false); 
 
     var sel = window.getSelection(); 
 
     sel.removeAllRanges(); 
 
     sel.addRange(range); 
 
    } else if (typeof document.body.createTextRange != "undefined") { 
 
     var textRange = document.body.createTextRange(); 
 
     textRange.moveToElementText(el); 
 
     textRange.collapse(false); 
 
     textRange.select(); 
 
    } 
 
}
div:focus { 
 
    background-color: Aqua; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div tabindex="-1" id="scripted"><a>Element A (script-only focusable)</a><a>Element B (script-only focusable)</a></div> 
 
<div id="test">Set Focus To Element Z</div>

関連する問題