質問

How do I make this code work with em values?

$(window).scroll(function() {
  if ($(window).scrollTop() > 100) {
    $('#scroller').css('top',$(window).scrollTop());
}
});

I want the 100 to be 10em, how can I do it?

役に立ちましたか?

解決

As ems are different based on the font size of an element, I'd assume you would be referencing the body font size.

Number(getComputedStyle(document.body, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]);

That will give you the font size in pixels, which you can multiple by however many ems you want to use.

Source: Converting em to px in Javascript (and getting default font size)

Example:

// scroll top using 10em
var tenEms = Number(getComputedStyle(document.body, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]) * 10;

$(window).scroll(function() {
  if ($(window).scrollTop() > tenEms) {
    $('#scroller').css('top',$(window).scrollTop());
  }
});

他のヒント

I'm afraid you don't. ScrollTop uses pixels:

ref: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

There is no way to easily translate between absolute pixels to relative ems.

The following code may help as given on [1]: http://jsfiddle.net/davidThomas/nEnNC/2/

function px2em(elem) {
var W = window,
    D = document;
if (!elem || elem.parentNode.tagName.toLowerCase() == 'body') {
    return false;
}
else {
    var parentFontSize = parseInt(W.getComputedStyle(elem.parentNode, null).fontSize, 10),
        elemFontSize = parseInt(W.getComputedStyle(elem, null).fontSize, 10);

    var pxInEms = Math.floor((elemFontSize / parentFontSize) * 100) / 100;
    elem.style.fontSize = pxInEms + 'em';
}
}

Also you can refer this question jQuery/JavaScript: convert pixels to em in a easy way

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top