我有以下功能允许用户按下允许他们编辑div
内容的按钮。点击.rename
按钮,div
变为可编辑状态,内容全部被选中,text-overflow:ellipsis
将替换为text-overflow:clip
。完成编辑后,用户点击“输入”,div
不再可编辑,text-overflow:ellipsis
将返回。
一切正常,但如果文字长度超过div
的尺寸,则现在不可编辑的div
会显示结尾的文字,而不是从头开始,即使我添加了其他代码,将插入符号移动到文本的开头。关于如何将div的视图移动到光标位置/文本开头的任何想法?
以下是代码:
//Makes tile contenteditable
$('.rename').click(
function() {
var renameThis = $(this).parent().parent().parent().children(':first'), range, selection;
$(renameThis).attr('contenteditable','true').selectText();
$(renameThis).css('text-overflow','clip');
});
//Makes the enter key close the tile editing
$('div.tile').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13) {
// insert 2 br tags (if only one br tag is inserted the cursor won't go to the next line)
var renameThis = this, range, selection;
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(renameThis);//Select the entire contents of the element with the range
range.collapse(true);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
$(renameThis).attr('contenteditable','false');
$(renameThis).css('text-overflow','ellipsis');
// prevent the default behaviour of return key pressed
return false;
}
});
jQuery.fn.selectText = function(){
this.find('input').each(function() {
if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) {
$('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
}
$(this).prev().html($(this).val());
});
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
&#13;
div.tile {
width:100px;
height:30px;
background-color:#0C6;
border-style:solid;
border-width: 0px;
border-color:#0C6;
margin: 0px 0px 5px 0px;
color:#FFF;
padding-left:10px;
line-height:30px;
font-size:25px;
cursor:pointer;
/*border-radius: 5px;*/
box-shadow: 0 3px #00994d;
float:left;
font-family: 'Open Sans Condensed', sans-serif;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="tile webtile">Netflix</div>
<div class="dropdown-this-content-container">
<div class="dropdown-this-content">
<div class="rename">Click here to rename</div>
</div>
</div>
</div>
&#13;
答案 0 :(得分:0)
想出来。我所要做的就是暂时将div的CSS更改为overflow:scroll
,将滚动位置设置为0,然后在更改之前更改回overflow:hidden
。