我正试图从自定义主题(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事件,但我仍然需要将.srink类添加到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提供:如何在WordPress中使用过滤器将类添加到html元素?,以满足我的需求,但无法使其正常工作。
请帮忙!
如果你使用的是genesis,你不需要非常复杂的代码来修改HTML输出,只需在网站标题前缀中添加一个过滤器,genesis是迄今为止最可定制的框架。
add_filter( 'genesis_attr_site-header', 'my_custom_genesis_header_class' );
function my_custom_genesis_header_class( $attributes ) {
$attributes['class'] .= ' shrink';
return $attributes;
}