简体   繁体   中英

Modify JavaScript to access variable

I'm playing around with some code which enlarges text based on the size of the div it's in. It can be seen here:

http://codepen.io/anon/pen/zZqXXd

$(function() {

  var outer = $('div'), inner = $('h1'),
  difference = outer.width()-inner.width(),
  ratio = outer.width()/inner.width(),
  style = 'translateX(' + difference/2 + 'px) ' + 'scale(' + ratio + ')';
  inner.css({'webkit-transform': style, transform: style});
});

However, I'm trying to modify it to use a variable with sizes in, not get it from the div. This was my attempt that doesn't seem to work:

$(function() {

  var width = "400",
  var inner = $('h1'),
  difference = width -inner.width(),
  ratio = width /inner.width(),
  style = 'translateX(' + difference/2 + 'px) ' + 'scale(' + ratio + ')';
  inner.css({'webkit-transform': style, transform: style});
});

You have to replace the comma ( ',' ) after var width = "400" with a semicolon. Your current code throws a syntax error.

The corrected code would be:

$(function() {

  var width = "400"; // <-----
  var inner = $('h1'),
  difference = width -inner.width(),
  ratio = width /inner.width(),
  style = 'translateX(' + difference/2 + 'px) ' + 'scale(' + ratio + ')';
  inner.css({'webkit-transform': style, transform: style});
});

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