javascript - 显示悬停在 wp 中的图像的特色帖子
问题描述
我正在尝试制作一个仅在将鼠标悬停在标题上后才显示帖子图像的简单网站。问题是我无法让我的 JS 工作。有了一些以前的提示,我在这里得到了关于如何进行此操作的技巧,我首先在 PHP 短代码片段中列出了所有带有 URL 作为 ID 的帖子图像(使其更容易比较):
// The Query
$the_query = new WP_Query( array( 'post_type' => 'post','posts_per_page' => -1 ) );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
//Useless
// echo '<li>' . get_the_title() . '</li>';
// echo '<li>' . get_permalink() . '</li>';
echo '<li>';
echo '<a href="' . get_permalink() . '">';
echo '<figure class="popUp" id="' . get_permalink() . '">';
the_post_thumbnail();
echo '</figure>';
echo '</a>';
echo '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
在 CSS 中,我将 PopUp 的显示属性设置为无。到目前为止,一切都按预期进行。但是现在 JS 进来了。我想获取一个悬停的帖子的 URL,如果它与我希望它显示的帖子的 URL(在 CSS 中的 ID)相同。当悬停停止时,我也希望图像消失。
document.getElementById("carousel").addEventListener('mouseover', function(event) {
var hoveredEl = event.target; // The actual element which was hovered.
if (hoveredEl.tagName !== 'A') { return; } // Ignore non links
const addCSS = s =>(d=>{d.head.appendChild(d.createElement("style")).innerHTML=s})(document);
// Usage:
addCSS("#" + hoveredEl + " { display: inline-block; }";)
});
document.getElementById("carousel").addEventListener('mouseout', function(event) {
var hoveredEl = event.target; // The actual element which was hovered.
if (hoveredEl.tagName !== 'A') { return; } // Ignore non links
const addCSS = s =>(d=>{d.head.appendChild(d.createElement("style")).innerHTML=s})(document);
// Usage:
addCSS("#" + hoveredEl + " { display: none; }";)
});
我将它作为短代码 JS 片段放在页面上,与 PHP 代码在同一个 DIV 中,但与悬停的链接不同(可能是 iss)。JS 代码中是否有明显的危险信号?
编辑:关闭图形标签并在特定 DIV 上使用事件侦听器。还是没有运气...
解决方案
尝试这样的事情(注意新hover-target
类):
// The Query
$the_query = new WP_Query( array( 'post_type' => 'post','posts_per_page' => -1 ) );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>';
echo '<a class='hover-target' href="' . get_permalink() . '">';
echo '<figure class="popUp" id="' . get_permalink() . '">';
the_post_thumbnail();
echo '</figure>';
echo '</a>';
echo '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
jQuery('.hover-target').hover(function(e) {
$(this).siblings('figure').show()
}, function(e){
$(this).siblings('figure').hide()
})
这假设缩略图默认隐藏,规则如下:
.popUp {
display: none;
}
这是因为您使用 jQuery 的hover()来传递两个单独的函数,一个 formouseenter
和一个 for mouseleave
。开mouseenter
,显示图像。在 上mouseleave
,隐藏图像。
推荐阅读
- python - 如何在读取文件但删除一个变量然后替换它时删除“\n”字符
- flutter - 无法设置回调函数。错误说:“DropDown”必须有一个方法体,因为“ListLayout”不是抽象的
- android - 如何在apache cordova中完成页面滑动
- django - serializer.save() 不将数据保存到管理数据库
- flutter - (使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。)错误
- sql - 如何在 BigQuery 中编写以下 SQL 查询
- python - 迭代到递归格式
- apache-spark - 在完成的 Spark 作业中“失败”是什么意思?
- sql - 从字符串的开头到结尾替换
- flutter - 使用 Dart/Flutter 将数据流式传输到大查询中