当文本框有内容时修改表单提交按钮样式——Jade/Pug问题
Hey there, I spot the exact issue right away—you're modifying the button's class the wrong way in your JavaScript! Let me break this down for you:
The Root Problem
You’re using btn.class = 'butOn' to change the button’s CSS class, but that’s not how DOM elements work. The class property on a DOM element isn’t directly accessible like that—you’re just adding a custom property to the JS object instead of updating the actual DOM’s class attribute. That’s why your CSS styles aren’t kicking in at all. Also, your logic has a small bug: you’re setting butOn in both the enabled and disabled branches, when you probably want butOff for the disabled state.
Fixed Code
First, update your Pug mixin to set the initial correct class for the disabled button:
mixin myForm() form(action="/tweet/add" method="POST" class="formclassname") textarea( name='text' id='textarea' maxlength="300" placeholder='What\'s happening?' ) // Add butOff to initial class since button starts disabled input( type="submit" id="button" value="Send It" class="button butOff" disabled = true ) script. var btn = document.getElementById('button'); var inpt = document.getElementById('textarea'); inpt.addEventListener("input", function(){ // Use trim() to ignore empty whitespace const hasContent = this.value.trim() !== ''; if (hasContent) { btn.disabled = false; btn.classList.remove('butOff'); btn.classList.add('butOn'); console.log('button enabled'); } else { btn.disabled = true; btn.classList.remove('butOn'); btn.classList.add('butOff'); console.log('button disabled'); } })
Even Cleaner Version (Optional)
You can simplify the class toggling using classList.toggle() with a second argument, which adds/removes the class based on a boolean:
inpt.addEventListener("input", function(){ const hasContent = this.value.trim() !== ''; btn.disabled = !hasContent; btn.classList.toggle('butOn', hasContent); btn.classList.toggle('butOff', !hasContent); console.log(hasContent ? 'button enabled' : 'button disabled'); })
Why This Works
classListis the standard API for manipulating DOM element classes—it directly updates the element’sclassattribute in the DOM, so your CSS rules will pick up the changes immediately.- Adding
trim()ensures that users can’t just type spaces to enable the button, which is a common edge case. - Setting the initial
butOffclass makes sure the button starts with the correct disabled styling right when the page loads.
内容的提问来源于stack exchange,提问作者Axle Max

