jQuery的.css()方法无法应用-webkit-transform。

3
我看不出这段代码有什么问题。计算窗口中心位置,然后将div变换为该位置(必须使用translate完成我的任务)。
首先让它在Chrome上运行,因此需要-webkit-前缀。
非常困惑为什么jQuery不能将内联样式应用到.logo div。已经包含了其他的故障排除实验并进行了注释。
语法问题?jsfiddlehere
var centerPosition = '';

function centerLogo(){
  var w_width = $(window).width();
  var w_height = $(window).height();
  var hCenter = (w_width / 2) - 150;
  var vCenter = (w_height / 2) - 150;
    console.log(hCenter);
    console.log(vCenter);
  var centerPosition = 'translate(' + hCenter + 'px, ' + vCenter + 'px);';
    console.log(centerPosition);
  $('.logo').css('-webkit-transform', centerPosition);

  // Try uncommenting the three examples below - they all work ...

  // $('.logo').css('background', 'blue');

  // centerPosition = 'blue';
  // $('.logo').css('background', centerPosition);

  // $('.logo').css('-webkit-transform', 'translate(10.85px, 45.56px)');

}

jQuery(document).ready(function($){
  centerLogo();
});

1
jQuery的css方法,在版本>=1.8.0中,会根据需要添加供应商前缀;您无需手动指定。 - Palpatim
1
在声明 centerPosition 时,请删除分号。http://jsfiddle.net/Palpatim/7f7rt/5/ - Palpatim
2个回答

1

$('.logo').css('-webkit-transform', centerPosition); 的正确语法在字符串内部不需要分号。尝试更改为:

var centerPosition = 'translate(' + hCenter + 'px, ' + vCenter + 'px);';

转换为:

var centerPosition = 'translate(' + hCenter + 'px, ' + vCenter + 'px)';

应该可以工作:http://jsfiddle.net/7f7rt/6/


这有什么帮助吗? - Krunal Patil
$('.logo').css('-webkit-transform', centerPosition); 的正确语法不应该在字符串内部加分号。 - Guolin
你确定吗,因为在 jsfiddle 上它没有工作...请再次检查。 - Krunal Patil
Alpesh 给出的答案是有效的,没有分号方面的问题。 - Krunal Patil
我怎么会错过那个?谢谢大家的帮助。也很高兴了解到jQuery前缀的知识。 - spacewindow

0

这肯定会起作用。

    var posElem = document.getElementById('logo'); // set id to div 

    var newStyle = '-webkit-transform: translate(' + hCenter + 'px, ' + vCenter + 'px);' +
   'transform: translate(' + hCenter + 'px, ' + vCenter + 'px);';
   posElem.setAttribute('style',newStyle);

在这一行添加注释:$('.logo').css('-webkit-transform', centerPosition); 并且不要忘记更改您的div的id为logo。 - cracker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接