How to dynamically add a style for text-align using jQuery

前端 未结 11 859
暗喜
暗喜 2020-12-08 04:19

I\'m trying to correct the usual IE bugs around CSS 2.1 and need a way to alter an elements style properties to add a custom text-align style.

Currently in jQuery yo

相关标签:
11条回答
  • 2020-12-08 04:23
    <!DOCTYPE html>
    <html>
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script>
          $( document ).ready(function() {
          $this = $('h1');
             $this.css('color','#3498db');
             $this.css('text-align','center');
             $this.css('border','1px solid #ededed');
          });
        </script>
    
      </head>
      <body>
          <h1>Title</h1>
     </body>
    </html>
    
    0 讨论(0)
  • 2020-12-08 04:29

    I usually use

    $(this).css({
        "textAlign":"center",
        "secondCSSProperty":"value" 
    });
    

    Hope that helps

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

    You have the right idea, as documentation shows:

    http://docs.jquery.com/CSS/css#namevalue

    Are you sure you're correctly identify this with class or id?

    For example, if your class is myElementClass

    $('.myElementClass').css('text-align','center');
    

    Also, I haven't worked with Firebug in a while, but are you looking at the dom and not the html? Your source isn't changed by javascript, but the dom is. Look in the dom tab and see if the change was applied.

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

    You could also try the following to add an inline style to the element:

    $(this).attr('style', 'text-align: center');
    

    This should make sure that other styling rules aren't overriding what you thought would work. I believe inline styles usually get precedence.

    EDIT: Also, another tool that may help you is Jash (http://www.billyreisinger.com/jash/). It gives you a javascript command prompt so you can ensure you easily test javascript statements and make sure you're selecting the right element, etc.

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

    $(this).css("text-align", "center"); should work, make sure 'this' is the element you're actually trying to set the text-align style to.

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

    Interesting. I got the same problem as you when I wrote a test version.

    The solution is to use jquery's ability to chain and do:

    $(this).width(500).css("text-align", "center");
    

    Interesting find though.

    To expand a bit, the following does not work

    $(this).width(500);
    $(this).css("text-align", "center");
    

    and results only in the width being set on the style. Chaining the two, as I suggested above, does seem to work.

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