元素滑块从 0 到底部(负数)开始,而不是在 Firefox 中从 0 到顶部

element slider start from 0 to bottom (negative) instead 0 to top in firefox

本文关键字:顶部 Firefox 中从 底部 元素 负数 开始      更新时间:2023-09-26

所有浏览器中的元素滑块从 0 到顶部开始(例如:0 to 500 ),这是页面方向left to right时,当页面方向right to left时,滑块从顶部开始到 0(例如:500 to 0)。
firefox是唯一一个在页面方向从0到底部(例如:0 to -500)负数right to left时不同的浏览器。

var box = document.getElementById('box');
var result = document.getElementById('result');
box.onscroll = function() {
  result.innerHTML = box.scrollLeft;
}
body {
  direction: rtl;
}
#box {
  width: 500px;
  height: 250px;
  margin: 0 auto;
  overflow-y: hidden;
  overflow-x: scroll;
}
#childBox {
  width: 1000px;
  height: 250px;
  background: url('http://images.all-free-download.com/images/graphiclarge/school_symbols_seamless_pattern_311368.jpg') repeat-x;
  overflow: hidden;
}
<div id="box">
  <div id="childBox"></div>
</div>
<div id="result"></div>

还有杰斯菲德尔。

如何让火狐像所有浏览器一样对待元素滑块?

现在这是我不知道的事情,很酷。甚至MDN也明确表示Firefox'是正确的行为。但是,如果所有其他浏览器的行为都如此,那么与众不同就没有意义了,尤其是对于像 scrollLeft 这样的旧规范。

无论如何,一种方法可以使Firefox像其他方法一样工作,并且涉及一个(公平地说,相当侵入性)技巧。Firefox 还支持非标准属性scrollLeftMax,这可能会派上用场,因为它节省了我们检查元素的计算样式的时间:如果一个元素是水平滚动的,但scrollLeftMax为零,那么它是从右到左的,需要调整:

if (!("scrollLeftMax" in Element.prototype)) return;
var scrollLeftDesc = Object.getOwnPropertyDescriptor(Element.prototype, "scrollLeft");
Object.defineProperty(Element.prototype, "scrollLeft", {
    get: function() {
        var diff = this.scrollWidth - this.clientWidth;
        return scrollLeftDesc.get.call(this) + (this.scrollLeftMax ? 0 : diff);
    },
    set: function(v) {
        var diff = this.scrollWidth - this.clientWidth;
        scrollLeftDesc.set.call(this, v - (this.scrollLeftMax ? 0 : diff));
        return v;
    }
});

如果需要或为了完整性,也应注意scroll方法:

var originalScroll = Element.prototype.scroll;
Element.prototype.scroll = function(x, y) {
    var diff = this.scrollWidth - this.clientWidth;
    originalScroll(x - (this.scrollLeftMax ? 0 : diff), y);
};

关键是了解何时应用它。我认为没有办法在不向 DOM 添加虚拟元素的情况下先发制人地检查这一点。