문제

I have the following code:

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'));

With credits to @Zword.

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

Example with 150vh, working correct.

Example with 140vh, not working correct.

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.

도움이 되었습니까?

해결책

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.

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;
};

To just get the value you can do

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top