简体   繁体   中英

Change letter and word spacing with jQuery

I have the following code to change the text style in a textarea:

HTML

    <!--text area-->

      <textarea placeholder="paste text here" size = "12" id="text" rows="5" cols="90" ></textarea>

      <!--text alter inputs-->

      <br/><br/>
letter spacing: <input type="number" placeholder="#" id="letterSpace"/>

<br/><br/>
word spacing: <input type="number" placeholder="#" id="wordSpace"/>

      <br/><br/>
line spacing: <input type="number" placeholder="#" id="lineSpace"/>

    <!--apply changes button-->

      <br/><br/><button id="go">update text!</button>

JAVASCRIPT (jQuery)

$("#go").click(function(){

   //SET VARS

  var letterSpace = $("#letterSpace").val();

  var wordSpace = $("#wordSpace").val();

  var lineSpace = $("#lineSpace").val();

  //UPDATE TEXT

   $("#text").css("letter-spacing", letterSpace);
   $("#text").css("word-spacing", wordSpace);
   $("#text").css("line-height", lineSpace);

});

and it works for the line-height but not for the letter or word spacing. Does anyone know why might this be? Thanks in advance!

jQuery css expects an object. you may need to enter something like this in your input:

{ "font-weight": "bold" }

and then use $(el).css(JSON.parse(wordSpace))

I tried your code ,you just need to define the units in your JQuery code.I tried the code given by you it works for me after changing this way.

 $("#go").click(function(){

   //SET VARS

  var letterSpace = $("#letterSpace").val();

  var wordSpace = $("#wordSpace").val();

  var lineSpace = $("#lineSpace").val();

  //UPDATE TEXT

   $("#text").css("letter-spacing", letterSpace+"px");
   $("#text").css("word-spacing", wordSpace+"px");
   $("#text").css("line-height", lineSpace+"px");

});

By appending px with the numbers it worked perfectly for me.

Please let me know if this is helpful for you.

Thanks

您必须为字母间距定义有效值:普通,长度,首字母,继承等,并为数字值后缀或在输入值中或输入值后附加“ px”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM