jQuery .focus doesn’t actually focus a newly created element

后端 未结 8 1887
清歌不尽
清歌不尽 2020-12-08 03:38

Let’s say I have this markup:

First paragraph

相关标签:
8条回答
  • 2020-12-08 03:52

    Instead of

    $("#newP").focus();  
    

    it should be used:

    window.location.href=window.location.href + "#newP";     
    
    0 讨论(0)
  • 2020-12-08 03:55

    I think the main answer is incorrect. DIV and P tags can receive focus providing you specify a tabindex property for them. i.e.

    <div class="someclass" tabindex="100">
    

    Once the tabindex is specified you can either tab to these elements or shift focus with .focus() .

    Using a scrollTo plugin seems like a bit of an overkill here.

    0 讨论(0)
  • 2020-12-08 03:55

    Only form elements and such can attain focus. If you want the browser to scroll down to that particular paragraph, there is no "default" way of doing so with jQuery, but there is a plugin for it at jQuery.ScrollTo and a blog explaining how to do it manually at Animated scroll with jQuery

    0 讨论(0)
  • 2020-12-08 03:56

    This code will avoid dependencies on other plugins and allow you to have it on any element.

    $('html, body').animate({ scrollTop: $("#newP").offset().top }, 500);
    
    0 讨论(0)
  • 2020-12-08 04:01

    I think what you're looking for is using the 'ScrollTo' plugin in jQuery. You can check it out here.

    You can specify what to scroll...

    $('div.pane').scrollTo(...);//all divs w/class pane
    

    Or just scroll the window:

    $.scrollTo(...);//the plugin will take care of this
    

    There are many different ways to specify the target position. These are:

    • A raw number
    • A string('44', '100px', '+=30px', etc )
    • A DOM element (logically, child of the scrollable element)
    • A selector, that will be relative to the scrollable element
    • A hash { top:x, left:y }, x and y can be any kind of number/string like above.

    Bonus: In digging up this information, I also found LocalScroll and SerialScroll (animates scrolling from one item to the next).

    0 讨论(0)
  • 2020-12-08 04:10

    You need to use a HTML page anchor not focus. Example:

    http://localhost/mypage.html#fourthP
    
    0 讨论(0)
提交回复
热议问题