我想听一堂课的变化。如果按钮“完全在视口中”,则触发单击。 $( "button.in-viewport.fully-in-viewport" ).trigger( "click" );
发现了许多其他选项,但没有任何更改。有什么建议吗?
答案 0 :(得分:1)
您可以使用MutationObserver
来观察类的变化,并根据新的类值做出反应:
向要观察的元素添加ref
:
<button ref="myButton">foo</button>
创建一种方法来处理观察到的更改:
methods: {
onClassChange(classAttrValue) {
const classList = classAttrValue.split(' ');
if (classList.includes('fully-in-viewport')) {
console.log('has fully-in-viewport');
}
}
}
创建一个MutationObserver
来观察class
元素的ref
属性的更改,这将调用上面定义的方法:
mounted() {
this.observer = new MutationObserver(mutations => {
for (const m of mutations) {
const newValue = m.target.getAttribute(m.attributeName);
this.$nextTick(() => {
this.onClassChange(newValue, m.oldValue);
});
}
});
this.observer.observe(this.$refs.myButton, {
attributes: true,
attributeOldValue : true,
attributeFilter: ['class'],
});
},
beforeDestroy() {
this.observer.disconnect();
},
Vue.component('foo', {
template: `<button ref="myButton" class="foo" @click="onClick">foo</button>`,
mounted() {
this.observer = new MutationObserver(mutations => {
for (const m of mutations) {
const newValue = m.target.getAttribute(m.attributeName);
this.$nextTick(() => {
this.onClassChange(newValue, m.oldValue);
});
}
});
this.observer.observe(this.$refs.myButton, {
attributes: true,
attributeOldValue : true,
attributeFilter: ['class'],
});
},
beforeDestroy() {
this.observer.disconnect();
},
methods: {
onClassChange(classAttrValue) {
const classList = classAttrValue.split(' ');
if (classList.includes('fully-in-viewport')) {
this.$refs.myButton.click();
}
},
onClick() {
requestIdleCallback(() => {
alert('foo clicked');
});
}
}
});
new Vue({
el: '#app',
data: () => ({
active: false
}),
})
.foo {
margin: 20px;
}
<script src="https://unpkg.com/vue@2.5.17"></script>
<div id="app">
<div>
<label>
<input type="checkbox" @change="active = !active">
<code>.fully-in-viewport</code> class
</label>
</div>
<foo :class="{'fully-in-viewport': active}"></foo>
</div>