显示在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的显示属性设置为none。到目前为止,一切都如预期。但现在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((传递两个独立的函数,一个用于mouseenter,一个为mouseleave。在mouseenter上,显示图像。在mouseleave上,隐藏图像。

最新更新