Visibility attribute question

前端 未结 3 1846
挽巷
挽巷 2021-02-03 23:17

What is the difference between

$(\"#myid\").attr(\"style\", \"visibility: hidden\")

and

$(\"#myid\").css(\"visibility\", \"hidden\"

相关标签:
3条回答
  • 2021-02-04 00:01

    Nothing. Just two ways to accomplish the same goal.

    The first will overwrite any existing style settings. If you had:

    <div style="font-weight: bold;" />
    

    It would become:

    <div sytle="visibility: hidden;" />
    

    The second will add the visibility setting to the existing styles. So:

    <div style="font-weight: bold;" />
    

    Woudl become:

    <div style="font-weight: bold; visibility: hidden;" />
    

    If there's no style attribute already set, then the two will produce the same end result.

    0 讨论(0)
  • 2021-02-04 00:17

    Doing this:

    $("#myid").attr("style", "visibility: hidden")
    

    Will leave only this style attribute, while doing this:

    $("#myid").css("visibility", "hidden")
    

    Will add (or set) this style attribute.

    Here's an example, the first will always result in this:

    style="visibility: hidden;"
    

    The second just adds visibility so your style may now be:

    style="width: 50px; color: red; visibility: hidden;"
    
    0 讨论(0)
  • 2021-02-04 00:24

    There isn't really any difference. $.css() is just a shortcut method for accessing the css style attribute of a dom element.

    http://api.jquery.com/css/

    EDIT: As justin pointed out, there is a difference in that the .attr() method will overwrite any existing style attributes.

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