jQuery的CSS calc回退函数

3
我将尝试编写一个jQuery函数,用于支持不支持CSS calc属性的浏览器。
目前为止,我有以下代码:
function calc($element, $xy, $logic, $difference) {
    var calc = $($object).$xy() $logic $difference;
    return calc;
}

if ($.browser.msie && $.browser.version <= 8) {
    var height = calc("body", "height", "-", "80");
    $("div#page").css("height", height);
}

我可以这一次没有函数也能完成任务,但是以后有了这个函数会非常有用。

很明显,下面这行代码:

var calc = $($object).$xy() $logic $difference;

...将会失败,但我不知道如何正确地传递变量。

如果有人对语法或如何编写此行有任何建议,那就太好了。

1个回答

7
您可以这样做:
function calc( selector, method, adjust ) {
    return $(selector)[method]() + adjust;
}

if( $.browser.msie  &&  $.browser.version <= 8 ) {
    var height = calc( 'body', 'height', -80 );
    $('div#page').css( 'height', height );
}

以下是该代码的一些注意事项:

  • You don't need the $ prefix on your function parameters. If you're writing jQuery code, I recomment using a $ prefix only on variables that are references to jQuery objects, e.g.

    var $foo = $('#foo');  // cache jQuery object for later use
    
  • Note the square brackets used with [method] - that's how you can call a method whose name is stored in a variable.

  • I combined the math operation and value into a single adjust parameter. You could do something fancier, but it would be good to see more examples of how this code would be used first.

还有一个建议:如果你不得不编写JavaScript代码来对那些不支持CSS calc的浏览器进行大小调整,为什么不在所有浏览器中都使用JavaScript代码呢?这样你只需要调试一个代码/样式设置而不是两个。


太棒了!再次感谢您提供的语法建议,这真的非常有用。关于您的建议,是的,这似乎是一个合理的方法。 - digiwig

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