需求定位:导航中实现子元素滚动到父元素的最左侧
解决方案:查找该子元素的offsetLeft值,然后让父元素滚动offsetLeft,parenDom.scrollLeft = childDom.offsetLeft
在vue原型上定义scrollToIndex函数
prototype.js
/** * 滚动到index * @param option = { * parentsDom //父元素 dom * childDom //子元素 dom * } */ Vue.prototype.scrollToIndex = function (options = {}) { let width = 0;
// 在全局找到
const el = document.getElementsByClassName(options.parentsDom), defaults = setDefault(options), elChild = document.getElementsByClassName(options.childDom); if (!judgeOptions(defaults)) { return; } if (defaults.x) { width = elChild[0].offsetLeft; } scrollLeft(el, width); }; function setDefault(options) { const defaults = { parentsDom: '', childDom: '', x: true, y: false, }; return Object.assign({}, defaults, options); } function judgeOptions(options) { console.log(options, 'options'); if (typeof options.parentsDom !== 'string' || typeof options.childDom !== 'string' || document.getElementsByClassName(options.parentsDom).length === 0 || document.getElementsByClassName(options.childDom).length === 0 ) { console.warn('Dom必须传是className并且存在'); return false; } return true; } function scrollLeft(el = '', width = 0) { if (!el) { return; } el[0].scrollLeft = width; }
.vue
this.scrollToIndex({ parentsDom: 'J-nav-select', childDom: 'J-nav-active', });