對于我的網站,我想在用戶單擊按鈕類別時自動向下滾動到一篇文章。
這是我的樹枝代碼。`
{% if category is not null and category|length > 0 %}
{% for categorie in category %}
<li class="nav-item category-link">
<button class="nav-link active" categoryId="{{categorie.id}}">{{categorie.name}}</button>
</li>
{% endfor %}
{% endif %}
</ul>
</div>
</div>
</nav>
<div class="">
{% for content in contents %}
<div contentId="{{content.id}}">
<h2 class="text-center">{{content.title}}</h2>
</div>`
這是我的 JS 部分。
var contentId = document.querySelector('div').getAttribute('contentId');
var categoryId = document.querySelector("button").getAttribute('categoryId');
if(categoryId){
categoryId.addEventListener('click', function() {
if (contentId === categoryId){
window.scrollTo(contentId);
}
});
}```
For information, actually in my database contentId related to categoryId have the same value. But for future they may not have the same value.
Thanks a lot for your help.
uj5u.com熱心網友回復:
非 JS 解決方案怎么樣?
要使用 JS 執行此操作,您必須對所有按鈕執行 querySelectorAll 并在每個按鈕上添加一個事件偵聽器,然后查詢相應的 contentId div,然后滾動到它。
一個非 JS 的解決方案可以是這樣的:
{% if category is not null and category|length > 0 %}
{% for categorie in category %}
<li class="nav-item category-link">
<a href="#{{categorie.id}}" class="nav-link active" categoryId="{{categorie.id}}">{{categorie.name}}</a>
</li>
{% endfor %}
{% endif %}
</ul>
</div>
</div>
</nav>
<div class="">
{% for content in contents %}
<div id="{{content.id}}" contentId="{{content.id}}">
<h2 class="text-center">{{content.title}}</h2>
</div>
uj5u.com熱心網友回復:
const contents = document.querySelectorAll('div[contentId]')
const categories = document.querySelectorAll("button[categoryId]")
categories.forEach(category => {
category.addEventListener('click', function() {
const categoryId = category.getAttribute('categoryId');
const content = Array.from(contents).find(content => content.getAttribute('contentId') === categoryId)
if (content){
content.scrollIntoView({ behavior: "smooth" });
}
)}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/496488.html
標籤:javascript
上一篇:如何將鉤子轉換為基于類的組件
