diff --git a/lib/commons/color/get-background-color.js b/lib/commons/color/get-background-color.js index f0ebdf2653..ac93dd301d 100644 --- a/lib/commons/color/get-background-color.js +++ b/lib/commons/color/get-background-color.js @@ -25,6 +25,21 @@ color.getBackgroundColor = function getBackgroundColor( const clientHeight = elm.getBoundingClientRect().height; const alignToTop = clientHeight - 2 >= window.innerHeight * 2; elm.scrollIntoView(alignToTop); + + // ensure element is scrolled into view horizontally + let center, scrollParent; + do { + const rect = elm.getBoundingClientRect(); + + // 'x' does not exist in IE11 + const x = 'x' in rect ? rect.x : rect.left; + center = x + rect.width / 2; + + if (center < 0) { + scrollParent = getScrollParent(elm); + scrollParent.scrollLeft = 0; + } + } while (center < 0 && scrollParent !== document.documentElement); } let bgColors = []; @@ -378,6 +393,36 @@ function contentOverlapping(targetElement, bgNode) { return false; } +/** + * Return the scrolling parent element + * @see https://stackoverflow.com/questions/35939886/find-first-scrollable-parent#42543908 + * @param {Element} element + * @param {Boolean} includeHidden + * @return {Element} + */ +function getScrollParent(element, includeHidden) { + var style = getComputedStyle(element); + var excludeStaticParent = style.position === 'absolute'; + var overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/; + + if (style.position === 'fixed') { + return document.documentElement; + } + for (var parent = element; (parent = parent.parentElement); ) { + style = getComputedStyle(parent); + if (excludeStaticParent && style.position === 'static') { + continue; + } + if ( + overflowRegex.test(style.overflow + style.overflowY + style.overflowX) + ) { + return parent; + } + } + + return document.documentElement; +} + /** * Determines whether an element has a fully opaque background, whether solid color or an image * @param {Element} node diff --git a/test/commons/color/get-background-color.js b/test/commons/color/get-background-color.js index 13d03a869c..e18327b8a1 100644 --- a/test/commons/color/get-background-color.js +++ b/test/commons/color/get-background-color.js @@ -646,6 +646,19 @@ describe('color.getBackgroundColor', function() { assert.notEqual(window.pageYOffset, 0); }); + it('scrolls horizontally into view when scroll is enabled', function() { + fixture.innerHTML = + '