【发布时间】:2023-03-06 04:17:01
【问题描述】:
我正在尝试从自定义主题 (file.js) 中删除特定的 jQuery 文件。该文件包含几个脚本,由于主题的自定义,不再需要这些脚本。唯一剩下的脚本使用 jQuery 基于滚动事件 (scrollTop) 向 HTML 元素添加额外的 CSS 类。代码如下所示:
$(window).scroll(function () {
if ($(document).scrollTop() > 1 ) {
$('.site-header').addClass('shrink');
} else {
$('.site-header').removeClass('shrink');
}
});
...它修改了:
<header class="site-header" itemscope="" itemtype="http://schema.org/WPHeader">
...成为:
<header class="site-header shrink" itemscope="" itemtype="http://schema.org/WPHeader">
...当最终用户滚动到页面顶部时。
不再需要 scrollTop 事件,但我仍然需要将 .shrink 类添加到 header 元素,我想在 WordPress 的 functions.php 文件中使用 PHP 来完成。
WordPress 模板可能包含多个 header html 元素,因此仅针对也具有 .site-header css 类的 header html 元素很重要。
我已尝试修改以下代码:
add_filter('the_content', 'add_text_input_classes', 20);
function add_text_input_classes($content)
{
$doc = new DOMDocument(); //Instantiate DOMDocument
$doc->loadHTML($content); //Load the Post/Page Content as HTML
$textareas = $doc->getElementsByTagName('textarea'); //Find all Textareas
$inputs = $doc->getElementsByTagName('input'); //Find all Inputs
foreach($textareas as $textarea)
{
append_attr_to_element($textarea, 'class', 'input');
}
foreach($inputs as $input)
{
$setClass = false;
if($input->getAttribute('type') === 'submit') //Is the input of type submit?
$setClass = 'btn';
else if($input->getAttribute('type') === 'text') //Is the input of type text?
$setClass = 'input';
if($setClass)
append_attr_to_element($input, 'class', $setClass);
}
return $doc->saveHTML(); //Return modified content as string
}
function append_attr_to_element(&$element, $attr, $value)
{
if($element->hasAttribute($attr)) //If the element has the specified attribute
{
$attrs = explode(' ', $element->getAttribute($attr)); //Explode existing values
if(!in_array($value, $attrs))
$attrs[] = $value; //Append the new value
$attrs = array_map('trim', array_filter($attrs)); //Clean existing values
$element->setAttribute($attr, implode(' ', $attrs)); //Set cleaned attribute
}
else
$element->setAttribute($attr, $value); //Set attribute
}
...这里由@maiorano84 提供:How to add a class to a html element using filters in WordPress?,以满足我的需要,但无法使其正常工作。
请帮忙!
【问题讨论】:
-
为什么不直接编辑主题文件呢?你用的是什么主题?它可能有一些过滤器来在某些元素上添加一个类
-
它是 Centric Pro、Genesis Child 主题的高度定制变体。
标签: php jquery html css wordpress