首页 > Jquery问题,点击一个元素,怎么设置光标在另一个元素里的位置?

Jquery问题,点击一个元素,怎么设置光标在另一个元素里的位置?

使用Jquery,点击A元素,怎么设置光标到B元素里,并且在最后的位置。(B元素是DIV,有contenteditable="true" 属性)
以下代码,点了A后,光标都是在B元素里最前面。。。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试</title>
<style type="text/css">
.aaa{ height:36px; line-height:36px; width:500px; margin:50px auto 0; border:1px solid #ccc; font-size:18px;background:#f5f5f5;cursor:pointer; }
.bbb{ width:380px; float:left; height:34px; border:1px solid #ccc; background:#fff; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
</head>

<body>


<div class="aaa">
	
    <div class="bbb" contenteditable="true">光标怎么才能在最后</div>
点我
</div>


<script type="text/javascript">
		$(function(){ 
		
			$(".aaa").click(function(){
				$(".bbb").focus();
	  		})
		})
</script>

</body>
</html>

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();
    }
}

$(function() {
    $(".aaa").click(function() {
        placeCaretAtEnd($('.bbb')[0]);
    })
})​

另外,建议“点我”不要是div.aaa下的文本节点,因为现在这样 div.aaa>div.bbb,你点击div.bbb时同样触发div.aaa的点击事件(冒泡),光标会直接跳到最后。将事件注册到 span#clickme 上就可以解决了。

http://jsfiddle.net/byz4f/

【热门文章】
【热门文章】