gpt4 book ai didi

javascript - .focus() 和 onfocus ="this.value = this.value"刷新后不会将光标移动到输入的末尾

转载 作者:行者123 更新时间:2023-12-01 08:35:53 24 4
gpt4 key购买 nike

每次刷新(使用超时)页面时,输入值保持不变,但光标跳转到值的开头。

我尝试使用 .click() 而不是 .focus() 它没有达到我想要的结果。

我已将 autofocus 添加到元素中,但这也没有帮助。

编辑:我注意到这似乎是 Google Chrome 浏览器的问题,我已经用 Safari 尝试过,它按预期工作。如果有人有任何建议让它在 Chrome 上运行,我们将不胜感激。

HTML 标签

<div class="searchContainer">
<h4>Find your favourite songs, artist or albums.</h4>
<input type="text" id="searchBar" class="searchBar" autofocus value="<?php echo $query; ?>" onfocus="this.value = this.value;" placeholder="Enter your search here">
</div>

JavaScript

<script>

$(".searchBar").focus();

$(function() {
// refreshes page on each time user types a word after 2000ms (2s)
var refresh;
$(".searchBar").keyup(function() {
clearTimeout(refresh);
//restarts refresher to wait for user to finish typing
refresh = setTimeout(function() {
var value = $(".searchBar").val();
changePage('search.php?query=' + value);
}, 2000);
})
})

</script>

我希望每次刷新后该值都显示在输入栏中,但光标停留在输入的末尾,以便用户可以从上次中断的位置继续输入。

(搜索栏通常如何工作,其中每个输入值都会刷新,以便立即显示输入内容的结果,但如果用户犯了错误,他们可以继续从他们停止的地方删除字符 )。

如果有人有任何想法,我们将非常欢迎。谢谢:)

最佳答案

你可以像这样添加到准备好的文档中,它会将输入的光标移动到末尾。

$(document).ready(function(){
$(".searchBar").focus();
var search = $(".searchBar").val();
$(".searchBar").val('');
$(".searchBar").val(search);
})

//$(".searchBar").focus();

$(function() {
// refreshes page on each time user types a word after 2000ms (2s)
var refresh;
$(".searchBar").keyup(function() {
clearTimeout(refresh);
//restarts refresher to wait for user to finish typing
refresh = setTimeout(function() {
var value = $(".searchBar").val();
changePage('search.php?query=' + value);
}, 2000);
})
})

$(document).ready(function(){
$(".searchBar").focus();
var search = $(".searchBar").val();
$(".searchBar").val('');
$(".searchBar").val(search);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="searchContainer">
<h4>Find your favourite songs, artist or albums.</h4>
<input type="text" id="searchBar" class="searchBar" autofocus value="Hien" placeholder="Enter your search here">
</div>

关于javascript - .focus() 和 onfocus ="this.value = this.value"刷新后不会将光标移动到输入的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55774675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com