SO网友:Hans V.
解决了问题!再次感谢admcfajn的帮助。我没有按照你的建议走正确的路线,但你的回答无疑为我指明了正确的方向,并引导我解决了我的问题。
下面是页面模板的完整代码,包括while循环中的JS,供任何偶然发现本文的人使用。
EDIT: 我忘了还为关闭按钮的id创建一个变量。下面我已经更改了代码,以包括关闭按钮:)
<?php
get_header();
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'category_name\' => \'attractions\',
\'posts_per_page\' => 10,
);
$arr_posts = new WP_Query( $args );
if ( $arr_posts->have_posts() ) :
while ( $arr_posts->have_posts() ) : $arr_posts->the_post();
get_posts($args);
echo $arr_posts->current_post . \'_\' . get_the_ID();
//vars below
$trigger_ID = \'trigger_\' . $arr_posts->current_post . \'_\' . get_the_ID();
$modal_ID = \'modal_\' . $arr_posts->current_post . \'_\' . get_the_ID();
$close_ID = \'close_\' . $arr_posts->current_post . \'_\' . get_the_ID();
?>
<button class="trigger" id="<?php echo $trigger_ID ?>"><?php the_title(); ?></button>
<div class="modal" id="<?php echo $modal_ID ?>">
<div class="modal-content">
<span class="close-button" id="<?php echo $close_ID ?>">×</span>
<h2><?php the_title(); ?></h2>
<div id="attraction-descrption" class="description">
<h3>Description</h2>
<p><?php the_field(\'description_field\'); ?></p>
</div>
<div id="attraction-opening-hours" class="opening-hours">
<h3>Opening Hours</h2>
<p><?php the_field(\'opening_hours_field\'); ?></p>
</div>
<div id="attraction-practical-information" class="practical-information">
<h3>Practical Information</h2>
<p><?php the_field(\'practical_information_field\'); ?></p>
</div>
</div>
</div>
<!--
JavaScript for button press below
-->
<script>
$(document).ready(function(){
var modal = document.querySelector("#<?php echo $modal_ID; ?>");
var trigger = document.querySelector("#<?php echo $trigger_ID; ?>");
var closeButton = document.querySelector("#<?php echo $close_ID ?>");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
});
</script>
<?php
endwhile;
endif;
?>
下面还有一个样式表,它可以在javascript将其打开或关闭时使这一切正常运行。
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 1rem 1.5rem;
width: 24rem;
border-radius: 0.5rem;
}
.close-button {
float: right;
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
cursor: pointer;
border-radius: 0.25rem;
background-color: lightgray;
}
.close-button:hover {
background-color: darkgray;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1.0);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
.modal.show-modal{
display: block !important;
}