用户需求
woocommerce 产品短描述为一段P文本,不想全部显示,限制117字符,后面自动加上..Full details,当点击Full details后显示全部,后面自动加上..Hide Full details,当点击Hide Full details后又恢复默认状态。
我们已知woocommerce 产品短描述的 class=”woocommerce-product-details__short-description” 段落为P,我们会应用到如下class
.woocommerce-product-details__short-description p
片段代码
<script> // Select the first <p> inside the div with the class 'woocommerce-product-details__short-description' const productDescription = document.querySelector('.woocommerce-product-details__short-description p'); const fullText = productDescription.innerText; const shortText = fullText.substring(0, 117); // Initially display shortened text with the toggle link productDescription.innerText = shortText; // Create the toggle link element const toggleLink = document.createElement("a"); toggleLink.href = "javascript:void(0)"; toggleLink.innerText = "...Full details"; toggleLink.style.color = "#0071bd"; toggleLink.style.cursor = "pointer"; toggleLink.style.textDecoration = "underline"; // Append the toggle link to the <p> element initially productDescription.appendChild(toggleLink); // Function to toggle between full and short text toggleLink.addEventListener("click", function() { if (toggleLink.innerText === "...Full details") { // Show full text and update link text to "Hide full details" productDescription.innerText = fullText; productDescription.appendChild(toggleLink); toggleLink.innerText = " Hide full details"; } else { // Show shortened text and update link text to "...Full details" productDescription.innerText = shortText; productDescription.appendChild(toggleLink); toggleLink.innerText = "...Full details"; } }); </script>