【问题标题】:jQuery focus() page scroll lengthjQuery focus() 页面滚动长度
【发布时间】:2013-01-24 04:58:10
【问题描述】:

我有这样的代码:

<a href="javascript://" onclick="$('#newMsgTxt').focus();">New message</a>
<div style="min-height: 1300px;"></div>
<textarea id="newMsgTxt"></textarea>
<div style="min-height: 500px;"></div>

这就是问题所在: 单击链接后,在不同的浏览器中,页面会滚动到不同的位置。

点击后textarea在屏幕上的位置示例:

Chrome: 居中
FF: 底部
Opera:强> 顶部

如何让所有浏览器都像 Chrome 一样工作?

【问题讨论】:

  • 尝试添加return false;在您的点击中
  • 旁注:总是尽量避免使用内联 JS,让你的代码可读性降低(几乎丑陋),很难调试,我需要喝咖啡

标签: javascript jquery css browser cross-browser


【解决方案1】:

试试这个。

onclick="$('#newMsgTxt').focus().val($('#newMsgTxt').val());

【讨论】:

  • 从同一个元素设置 val 的目的是什么?是不是光标会在上一个内容的末尾?
  • 是的。可能是这里的问题!
【解决方案2】:

HTML:

<a href="" id="newMessage">New message</a>

jQuery :

$(document).ready(function() {
    $('#newMessage').click(function(e) {
        e.preventDefault();
        $('#newMsgTxt').focus();
    });    
});

http://jsfiddle.net/soyuka/jxZw2/

【讨论】:

    【解决方案3】:
    $('a').click(function(e){
        e.preventDefault();
        var o = $('#newMsgTxt').focus().offset().top, $w = $(window);
        $w.scrollTop(o - ($w.height() / 2));
    });
    

    http://jsfiddle.net/2BHRw/

    【讨论】:

    • 当没有有效的 href 时,e.preventDefault 是必要的吗?
    • 是的,但如果您希望链接在没有 JS 的情况下工作,添加它可能会很有用。 (在这种情况下,你得到了一点)
    【解决方案4】:

    这是因为滚动位置不同,

    您可以通过点击link 使用console.log(window.scrollY) 进行测试 因此,您必须为此编写代码以使其居中对齐。

    而且代码是这样的

    $(function() {
        $('a').click(function(e){
            $('#newMsgTxt').focus();
            var offsetTop = offset().top; 
            $(window).scrollTop(offsetTop - ($(window).height() / 2));
        });
    });
    

    你的 html 喜欢:

    <a href="javascript://">New message</a>
    <div style="min-height: 1300px;"></div>
    <textarea id="newMsgTxt">gfg</textarea>
    <div style="min-height: 500px;"></div>
    

    【讨论】:

      【解决方案5】:

      嗨试试下面的代码……我的命名不好……所以,根据你的想法替换。

      <!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>
          <title></title>
          <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
         <script>
      
             function test() {
                 var o = $('#newMsgTxt').focus().offset().top, $w = $(window);
                      $w.scrollTop(o - ($w.height() / 2));
             }
         </script>
      </head>
      <body>
      <a  onclick="test();">New message</a>
      <div style="min-height: 1300px;vertical-align:top;"></div>
      <textarea id="newMsgTxt" ></textarea>
      <div style="min-height: 500px;"></div>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        相关资源
        最近更新 更多