我制作了一个侧边栏,我需要隐藏它并用它的类方法显示。从控制台调用方法Sidebar.show()
时,会删除元素的sb-hidden
- 类,以使其可见。
this.htmlElement.classList.toggle('sb-hidden', false)
但是,从代码中的' click' -event-handler调用Sidebar.show()
方法时,不会发生这种情况。
clickButton.addEventListener('click', () => {
blogSidebar.show()
})
点击clickButton
时为什么侧边栏不显示?
if (!("path" in Event.prototype))
Object.defineProperty(Event.prototype, "path", {
get: function() {
var path = [];
var currentElem = this.target;
while (currentElem) {
path.push(currentElem);
currentElem = currentElem.parentElement;
}
if (path.indexOf(window) === -1 && path.indexOf(document) === -1)
path.push(document);
if (path.indexOf(window) === -1)
path.push(window);
return path;
}
});
class Sidebar {
constructor() {
this.htmlElement = document.createElement('div')
this.htmlElement.className = 'sidebar'
this.contentElement = document.createElement('div')
this.contentElement.className = 'sb-content'
addEventListener('click', (event) => {
var inSidebar = false
for (var i = 0; i < event.path.length; i++) {
if(event.path[i] == this.htmlElement){
inSidebar = true
break;
}
}
if(!inSidebar){
this.hide()
}
})
document.body.appendChild(this.htmlElement)
}
show(){
this.htmlElement.classList.toggle('sb-hidden', false)
console.log(this)
}
hide(){
this.htmlElement.classList.toggle('sb-hidden', true)
}
addAction(action, element){
switch (action) {
case 'show':
element.addEventListener('click', (event) => {
this.show()
})
break;
case 'hide':
element.addEventListener('click', (event) => {
this.hide()
})
break;
default:
}
}
}
var clickButton = document.getElementById('clickbutton')
const blogSidebar = new Sidebar()
clickButton.addEventListener('click', () => {
blogSidebar.show()
})
addEventListener('load', () => {
blogSidebar.show()
})
&#13;
body{
background-color: #000;
}
.sidebar{
position: fixed;
top: 0;
right: 0;
width: 30vw;
height: 100%;
background-color: #fff;
z-index: 999999999;
transition: right 0.3s;
}
.sb-content{
}
.sb-hidden{
right: -30vw;
}
&#13;
<button type="button" name="button" id="clickbutton">Show sidebar</button>
&#13;