首页 > 解决方案 > 按顺序排列的 JavaScript 事件

问题描述

我有一个按钮,这个按钮应该包装文本并解开它,我怎样才能让按钮在第一次单击时解开文本,然后在下一次单击时包装它?包装是由 property 完成的white-space

// split the state into two chunks
function fullView(e) {
        // check if the element is the targeted or not
    if (e.target.parentElement.className == 'note') {
          // first state with the un-wrap text
         if(e.target.style.whiteSpace == 'normal'){
         // convert it to wraped
            document.querySelector(".note-content").style.whiteSpace = "nowrap";
        }else {
        // convert it to un-warped text
            document.querySelector(".note-content").style.whiteSpace = "normal";
        }
    }
}
<li class="note">
    <p class="note-content"> 
        Hello, World Note !! 
        Hello, World Note !! 
        Hello, World Note !! 
        Hello, World Note !! 
        Hello, World Note !! 
        Hello, World Note !! 
        Hello, World Note !! 
        Hello, World Note !!
    </p> 
</li>

标签: javascripthtmldom-events

解决方案


从 的内容来看,我假设您已将fullView其设置为. 如果是这样,最简单的方法是定义一个 CSS 类:click.note-content

.nowrap {
    white-space: nowrap;
}

...在 中fullView,切换它:

function fullView(e) {
  e.target.classList.toggle("nowrap");
}

现场示例:

// split the state into two chunks
function fullView(e) {
  e.target.classList.toggle("nowrap");
}
document.querySelector(".note-content").addEventListener("click", fullView);
.nowrap {
  white-space: nowrap;
}
<li class="note">
                 <p class="note-content"> 
                    Hello, World Note !! 
                    Hello, World Note !! 
                    Hello, World Note !! 
                    Hello, World Note !! 
                    Hello, World Note !! 
                    Hello, World Note !! 
                    Hello, World Note !! 
                    Hello, World Note !!
                    </p> 
</li>


推荐阅读