日期:2014-05-16  浏览次数:20342 次

可编辑的div,focus之后,光标怎么定位到文本最后?
使用了contenteditable=true的div,focus之后,会在最前的

------解决方案--------------------
我跟你一样,也碰到了这样的问题,后来我就想:当文本框没有值的时候,光标会停在最前;当向文本框输入值的时候,光标就会停在当前输入的位置。如果现在能够模拟出这种状态,那么问题就可以迎刃而解了。那么就让文本框先获得焦点,然后再改变文本框中的值就可以实现了。看看下面这段代码,就是这个思想。
HTML code

<html>
<body>
<input id="input" type="text" value="OK, no problem."/>
<input type="button" value="focus" onclick="setFocus('input',true)"/>
<input type="button" value="blur" onclick="setFocus('input',false)"/>
<script type="text/javascript">
function setFocus(id, yes) {
    var obj = document.getElementById(id);
    if (yes) {
        obj.focus();
        obj.value = obj.value;
    } else {
        obj.blur();
    }
}
</script>
</body>
</html>