jQuery .css(“left”) returns “auto” instead of actual value in Chrome

前端 未结 5 1532
感情败类
感情败类 2020-11-30 14:49

I have div element with left and top defined, without absolute position, and I want to read the left and top values using jQuery.

Using $(\"#M

相关标签:
5条回答
  • 2020-11-30 15:21

    add

    position: absolute;
    

    or

    position: relative;
    

    to the element you use left on

    0 讨论(0)
  • 2020-11-30 15:30

    I know this is an old post, but I ran into this same problem and thought I would suggest a couple of solutions. It seems that this problem is not specific to Chrome, as I was able to reproduce in Firefox as well.

    I was able to solve this one of two ways. Either place you CSS styles in the same file as your HTML, instead of using a separate CSS file. OR, call the function inside of window.onload. Looks like the values are not available to the browser until everything has loaded, IF the styles are in an external style sheet.

    Hope this is helpful.

    0 讨论(0)
  • 2020-11-30 15:34

    It is strange behavior for jQuery. But you can use native javascript methods to get css values:

    $("#Panel1")[0].style.left
    

    This expression will return corresponding css property.

    0 讨论(0)
  • 2020-11-30 15:38

    As discussed in the comments, setting left to auto for a position: static sounds somehow right, seeing as left has no meaning in the context.

    As to why Chrome and IE return different values: .css() provides a unified gateway to the browsers' computed style functions, but it doesn't unify the way the browsers actually compute the style. It's not uncommon for browsers to decide such edge cases differently.

    As to why jQuery 1.4.2 and 1.4.3 do this differently, I do not know for sure, but there's this in 1.4.3's release notes:

    Nearly the entire CSS module has been rewritten focusing entirely on extensibility. You can now write custom CSS plugins that extend the functionality provided by .css() and .animate().

    0 讨论(0)
  • 2020-11-30 15:42

    Try $("your selector").position().top;

    0 讨论(0)
提交回复
热议问题