使用jQuery在vh中添加/减去固定值到元素left属性集 [英] Add/subtract fixed value to elements left property set in vh with jQuery

查看:236
本文介绍了使用jQuery在vh中添加/减去固定值到元素left属性集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

HTML:

<div id="my-div"></div>

CSS:

#my-div{
display: none;
position: absolute;
left: 150vh;
bottom: -150px;
}

jQuery:

$.fn.vhLeft = function(property,unit){
var wpx = this.css(property).replace(/[^0-9]+/g,"");
var temp = $('<div />').css({
    left:'1'+unit, 
    position: 'absolute'
});
$('body').append(temp);
var oneEm = temp.css(property).replace(/[^0-9]+/g,"");
temp.remove();
var value = wpx/oneEm;
return (Math.round(value*100))+unit;
};
// You could now get your value like
alert($('#my-div').parseInt(vhLeft)('left','vh'));

赠送@Zword。

首先,它似乎theres什么问题的功能。使用一些值它的工作,有一些值,它不返回正确的值。

First off it seems theres something wrong with the function. With some values it works, with some values it doesnt return the right value.

具有150vh的示例,工作正常。

140vh的示例,无法正常工作。

基本上我需要能够添加或减去 12 $ c> vh 的价值左属性#my-div 一个元素。

Basically what i need is to be able to add or subtract 12 to/off the current vh value for the left property of #my-div on click of an element.

推荐答案

更改插件一点使用 getComputedStyle 但是注意,你必须为IE8和下面的polyfill,但它会做一个更好的工作,返回正确的样式比jQuery似乎这里做。

Change the plugin a little to use getComputedStyle, but note that you'll have to polyfill that for IE8 and below, but it will do a better job of returning the correct styles than jQuery seems to do here.

,添加一个setter,只是添加另一个参数和一个条件

Also, to add a setter, just add another argument and a condition

$.fn.vhLeft = function(property , unit, adder){
    var el1 = this.get(0), el2 = document.createElement('div');

    $('body').append(el2);
    el2.style[property] = 1 + unit;

    var px1 = parseFloat(window.getComputedStyle(el1).getPropertyValue(property).replace(/[^0-9\,\.\-]/g, '')),
        px2 = parseFloat(window.getComputedStyle(el2).getPropertyValue(property).replace(/[^0-9\,\.\-]/g, '')),
        tot = Math.round( px1 / px2 );

    if (adder) {
        tot = tot + (adder);
        el1.style[property] = tot + unit;
    }

    $(el2).remove();

    return tot;
};

要获得您可以做的值

var vh = $('#my-div').vhLeft('left','vh');

并添加/减去值(这也会返回新值)

and to add / subtract to the value (this also returns the new value)

$('#my-div').vhLeft('left','vh', 12); // adds 12, returns 162

$('#my-div').vhLeft('left','vh', -12); // subtracts 12, returns 138

FIDDLE

这篇关于使用jQuery在vh中添加/减去固定值到元素left属性集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆