我有一个很好用的 javascript 代码,它可以将页面滚动到特定收藏项的 ID。但是滚动只是从一个项目跳到另一个项目。我一个人想做但做不到的是做一个平滑的滚动。我尝试 html 流畅的行为,但它在移动设备上不起作用,所以我想在 javascript 中使用它。这是我的代码:
//index db
const favoriteButtonAttr = 'data-add-to-favorite';
const isFavorite = 'data-is-favorite';
const listSelector = '[data-my-favorites]';
class FavoritesList {
constructor () {
this.storageName = 'favoritesList';
this.list = this.initList();
}
initList () {
if (window.localStorage.getItem(this.storageName)) {
// todo: repetitive parse?
const list = JSON.parse(window.localStorage.getItem(this.storageName));
updateHtmlList(list);
return list;
} else {
return [];
}
}
initButton(button) {
const id = parseInt(button.getAttribute(favoriteButtonAttr));
button.addEventListener('click', (event) => {
const button = event.target;
!inArray(id, this.list) ? this.list.push(id) : removeFromArray(id, this.list);
setState(id, this.list);
this.updateList();
})
function setState (id, list) {
return button.toggleAttribute(isFavorite, inArray(id, list));
}
setState(id, this.list);
return button;
}
updateList() {
setLocalStorage(this.storageName, this.list);
updateHtmlList(this.list);
}
}
function updateHtmlList(list) {
if(list.length > 0) {
// lastest favorites on top & don't modify original list;
const newList = list.slice(0).reverse();
favoritesHTMLElement.innerHTML = '';
listItems = document.createElement('ul');
newList.forEach( item => {
let htmlLi = document.createElement('lis');
htmlLis.innerHTML = item;
favoritesHTMLElement.appendChild(htmlLis);
});
} else {
favoritesHTMLElement.innerHTML = '';
}
}
function inArray(element, array) {
return array.indexOf(element) != -1;
}
function removeFromArray(element, array) {
array.splice(array.indexOf(element), 1);
}
function setLocalStorage(key, value) {
console.log(value)
window.localStorage.setItem(key, JSON.stringify(value));
}
const buttons = document.querySelectorAll(`[${favoriteButtonAttr}]`);
const favoritesHTMLElement = document.querySelector(listSelector);
let favorites = new FavoritesList();
buttons.forEach( button => favorites.initButton(button) );
function updateHtmlList(list) {
if(list.length > 0) {
// lastest favorites on top & don't modify original list;
const newList = list.slice(0).reverse();
favoritesHTMLElement.innerHTML = '';
listItems = document.createElement('ul');
newList.forEach( item => {
let htmlLis = document.createElement('lis');
htmlLis.innerHTML = '<a href="#'+item+'" class="go-to-link">💛 '+item+'</a>';
favoritesHTMLElement.appendChild(htmlLis);
});
} else {
favoritesHTMLElement.innerHTML = '';
}
}
我在 html 中尝试了流畅的行为,但它在移动设备上不起作用,所以我需要在 javascript 代码中使用它。
最佳答案
要使用平滑滚动,请在您的 CSS 中添加以下内容。
html {
scroll-behavior: smooth;
}
这将使整个网页(html
标记中的所有内容)平滑滚动。
关于javascript - 在本地存储收藏夹列表中添加平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71625337/