如何在 JS 中单击省略号时在模式中显示整个文本?
How to show entire text in a modal on click of ellipsis in JS?
我正在编写如下所示的 php 代码,其中我在特定字数限制后添加了 省略号 (...)。
<?php
$programs = array();
foreach ( $xml_files as $file ) {
$xml = simplexml_load_file($src_dir."/".$file) or die('Unable to load XML');
$path_title_en = $xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$path_description_en = $xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$programs[] = array( "episode_title" => (string)$path_title_en,
"description" => (string)$path_description_en;
}
$program["episode_title"] = substr($program["episode_title"],0,50).' <a href="">(...)</a>'; /* ellipsis is added after a particular word limit */
$program["description"] = substr($program["description"],0,100).' <a href="">(...)</a>'; /* ellipsis is added after a particular word limit */
?>
<table>
<tr>
<td style="width:8%; text-align:center;"><?php echo $program["episode_title"]; ?></td> /* Line A */
<td style="width:8%; text-align:center;"><?php echo $program["description"]; ?></td> /* Line B */
</tr>
</table>
行#A显示以下文字:
中的洪水问题
ABCSGSGSGSGSGSG 和
SHSHSGFASGXDS (...)
问题陈述:
我想知道我需要添加什么 JS 代码,以便在 单击 (...) 时,全文显示在模态中,例如 this .
您应该使用经过修改的演示才能在该模式中使用自定义文本。 https://www.w3schools.com/code/tryit.asp?filename=G4QNZITEFN72
然后修改您的代码,以便能够在该模式中发送全文 window
<?php
$programs = array();
foreach ( $xml_files as $file ) {
$xml = simplexml_load_file($src_dir."/".$file) or die('Unable to load XML');
$path_title_en = $xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$path_description_en = $xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$programs[] = array("episode_title" => (string) $path_title_en, "description" => (string)$path_description_en;);
}
foreach ( $programs as $program ) {
$episode_title = substr($program["episode_title"],0,50).' <a href="#show_full_title" onClick="showModal(\''.htmlspecialchars($program["episode_title"]).'\')">(...)</a>'; /* ellipsis is added after a particular word limit */
$description = $program["description"] = substr($program["description"],0,100).' <a href="#show_full_description" onClick="showModal(\''.htmlspecialchars($program["description"]).'\')">(...)</a>'; /* ellipsis is added after a particular word limit */
?>
<table>
<tr>
<td style="width:8%; text-align:center;"><?php echo $episode_title; ?></td> /* Line A */
<td style="width:8%; text-align:center;"><?php echo $description; ?></td> /* Line B */
</tr>
</table>
<?php } ?>
向该标签添加一个 onClick 处理程序,它将调用带全文的 showModal 函数。
我只是用模态 UI、脚本和少量逻辑来更新您的代码以将内容传递给模态。试试这个我希望它能帮助你。谢谢
var modal = document.getElementById("readMoreModal");
var btn = document.getElementsByClassName("readMoreModalTrigger")[0];
var closeBtn = document.getElementById("close");
// When the user clicks on <span> (x), close the modal
closeBtn.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Append Readmore content in modal
function readMoreMethod(text) {
document.getElementById("modal-content-append").innerHTML = text;
modal.style.display = "block";
}
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#close:hover,
#close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<?php
$programs = array();
foreach ( $xml_files as $file ) {
$xml = simplexml_load_file($src_dir."/".$file) or die('Unable to load XML');
$path_title_en = $xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$path_description_en = $xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$programs[] = array( "episode_title" => (string)$path_title_en,
"description" => (string)$path_description_en;
}
$program["episode_title"] = substr($program["episode_title"],0,50).' <a class="readMoreModalTrigger" href="JavaScript:Void(0);" onclick="readMoreMethod('$program["episode_title"]')">(...)</a>'; /* ellipsis is added after a particular word limit */
$program["description"] = substr($program["description"],0,100).' <a
class="readMoreModalTrigger" href="JavaScript:Void(0);" onclick="readMoreMethod('$program["description"]')">(...)</a>'; /* ellipsis is added after a particular word limit */
?>
<table>
<tr>
<td style="width:8%; text-align:center;"><?php echo $program["episode_title"]; ?><a class="readMoreModalTrigger" href="JavaScript:Void(0);" onclick="readMoreMethod('tadsad sadsad asdasd asdas dsad ')" href="">(...)</a></td>
<td style="width:8%; text-align:center;"><?php echo $program["description"]; ?></td>
</tr>
</table>
<!-- The Modal -->
<div id="readMoreModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="close">×</span>
<p id="modal-content-append"></p>
</div>
</div>
这是我对字符串提取的完全测试实现以及来自 w3schools 演示的所需模态功能:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
.triggersModal {
padding: 50px;
border: solid 2px black;
margin: 50px;
cursor: pointer;
}
/* The Modal (background) */
#myModal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#modalCloser {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#modalCloser:hover,
#modalCloser:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<?php
$episodes = [
[
'episode_title' => 'Lorem Ipsum',
'description' => "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."],
[
'episode_title' => "The standard 'Lorem Ipsum' passage, used since the 1500s",
'description' => '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
]
];
foreach ($episodes as $index => $episode) { ?>
<div class="triggersModal" data-index="<?php echo $index; ?>">
<div><?php
if (strlen($episode['episode_title']) <= 50) {
echo $episode['episode_title'];
} else {
echo substr($episode['episode_title'], 0, 50) , "(...)";
}
?></div>
<div><?php
if (strlen($episode['description']) <= 100) {
echo $episode['description'];
} else {
echo substr($episode['description'], 0, 100) , "(...)";
}
?></div>
</div>
<?php } ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="modalCloser">×</span>
<p id="modalFullTitle"></p>
<p id="modalFullDescription"></p>
</div>
</div>
<script>
// Transfer data from php to javascript
let episodes = <?php echo json_encode($episodes); ?>,
classname = document.getElementsByClassName("triggersModal"),
modal = document.getElementById("myModal");
// Bind value insertion and modal display to onclick event of every element with named class
for (let i = 0, len = classname.length; i < len; ++i) {
classname[i].onclick = function() {
let index = this.getAttribute('data-index');
document.getElementById("modalFullTitle").innerHTML = episodes[index]['episode_title'];
document.getElementById("modalFullDescription").innerHTML = episodes[index]['description'];
modal.style.display = "block";
}
}
// Close the modal
document.getElementById("modalCloser").onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
您需要用您的文件碎片替换我的硬编码输入(上方)。要创建 your $episodes
数组并使用单个循环显示主层的内容,请在 <body>
标记内使用它来显示可点击的阅读更多框:
<?php
$episodes = [];
$index = 0;
foreach ($xml_files as $file) {
$xml = simplexml_load_file("{$src_dir}/{$file}");
if (!$xml) {
continue;
}
$episode_title = (string)$xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$description = (string)$xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$episodes[] = ['episode_title' => $episode_title, 'description' => $description]; // used downscript to deliver data to clientside/js
?>
<div class="triggersModal" data-index="<?php echo $index; ?>">
<div>
<?php
if (strlen($episode_title) <= 50) {
echo $episode_title;
} else {
echo substr($episode_title, 0, 50) , "(...)";
}
?>
</div>
<div>
<?php
if (strlen($description) <= 100) {
echo $description;
} else {
echo substr($description, 0, 100) , "(...)";
}
?>
</div>
</div>
<?php
++$index;
}
?>
注意事项:
- 所有点击事件都写在脚本块中,而不是在 html 中,以保持整洁和可读。
- 仅当字符串有足够的长度时才需要使用省略号。
- 使用
json_encode()
. 将数据从php传递给js
- 不要使用
die()
。
- 我的偏好是不命名只会使用一次的变量(在 php 或 js 中)。有一些例外,但这是我的默认哲学。
- 由于查找数组 (
episodes
) 是一个索引数组,从被单击的元素传递的唯一相关值是索引。 data-
属性是维护主显示和要在模态中显示的数据之间的关系。
- 不推荐使用
<table>
标签显示 non-tabular 内容。我对页面和模态的样式所做的很少。我不想偏离您提供的演示太远。
- HTML 需要标识的元素应包含一个
id
以便于 javascript 定位。在多个位置出现的元素应包含 class
.
- 测试我的脚本后,在主页或模式中显示引用文本没有问题。
- 我试图保留语法 simple/readable,但我通常更喜欢 php 和 js 中的三元运算符(内联条件)。有些人在显示 php 时更喜欢 shorthand
<?=
和 ?>
。我对此也很满意;选择你喜欢的。
- 最后但并非最不重要的一点是,如果您的输入字符串来自不安全的渠道,或者如果它们包含 html,它会改进您的应用程序的 stability/security 编码 html 实体使用
htmlspecialchars($string, ENT_QUOTES, 'UTF-8')
显示在屏幕上的任何字符串( 在计算字符串长度之后,但在显示之前 )。这是一个很好的参考:
这是我的源代码转移到可运行的 Whosebug 片段:
// Transfer data from php to javascript
let lookup = [{"episode_title":"Lorem Ipsum","description":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},{"episode_title":"The standard 'Lorem Ipsum' passage, used since the 1500s","description":"\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\""}],
classname = document.getElementsByClassName("triggersModal"),
modal = document.getElementById("myModal");
// Bind value insertion and modal display to onclick event of every element with named class
for (let i = 0, len = classname.length; i < len; ++i) {
classname[i].onclick = function() {
let index = this.getAttribute('data-index');
document.getElementById("modalFullTitle").innerHTML = lookup[index]['episode_title'];
document.getElementById("modalFullDescription").innerHTML = lookup[index]['description'];
modal.style.display = "block";
}
}
// Close the modal
document.getElementById("modalCloser").onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
.triggersModal {
padding: 50px;
border: solid 2px black;
margin: 50px;
cursor: pointer;
}
/* The Modal (background) */
#myModal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#modalCloser {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#modalCloser:hover,
#modalCloser:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="triggersModal" data-index="0">
<div>Lorem Ipsum</div>
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the (...)</div>
</div>
<div class="triggersModal" data-index="1">
<div>The standard 'Lorem Ipsum' passage, used since the(...)</div>
<div>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore(...)</div>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="modalCloser">×</span>
<p id="modalFullTitle"></p>
<p id="modalFullDescription"></p>
</div>
</div>
</body>
</html>
已调整为单独显示单元格文本的另一个可运行片段...
// Transfer data from php to javascript
let lookup = [{"episode_title":"Lorem Ipsum","description":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},{"episode_title":"The standard 'Lorem Ipsum' passage, used since the 1500s","description":"\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\""}],
classname = document.getElementsByClassName("triggersModal"),
modal = document.getElementById("myModal");
// Bind value insertion and modal display to onclick event of every element with named class
for (let i = 0, len = classname.length; i < len; ++i) {
classname[i].onclick = function() {
let index = this.getAttribute('data-index'),
content = this.getAttribute('data-content');
document.getElementById("modalText").innerHTML = lookup[index][content];
modal.style.display = "block";
}
}
// Close the modal
document.getElementById("modalCloser").onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
.box {
padding: 50px;
border: solid 2px black;
margin: 50px;
}
.triggersModal {
cursor: pointer;
}
/* The Modal (background) */
#myModal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#modalCloser {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#modalCloser:hover,
#modalCloser:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="box">
<div class="triggersModal" data-index="0" data-content="episode_title">Lorem Ipsum</div>
<div class="triggersModal" data-index="0" data-content="description">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the (...)</div>
</div>
<div class="box">
<div class="triggersModal" data-index="1" data-content="episode_title">The standard 'Lorem Ipsum' passage, used since the(...)</div>
<div class="triggersModal" data-index="1" data-content="description">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore(...)</div>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="modalCloser">×</span>
<p id="modalText"></p>
</div>
</div>
</body>
</html>
这里是上述 php 执行的 pastebin 转储:https://pastebin.com/YnhNq6rD
这是给你的HTML/CSS/JS。
const trigger = document.querySelector(".trigger");
trigger.addEventListener("click", () => {
const fullTextSibling = trigger.previousElementSibling;
fullTextSibling.classList.add("active");
const closeModal = document.querySelector(".full_text > div > button");
closeModal.addEventListener("click", () => {
fullTextSibling.classList.remove("active");
});
});
.full_text {
display: none;
}
.full_text > div {
min-width: 300px;
min-height: 100px;
background: white;
padding: 20px;
border-radius: 10px;
}
.full_text.active {
display: flex;
background: #80808069;
width: 100%;
height: 100vh;
position: fixed;
top: 0;
align-items: center;
justify-content: center;
}
<div class="container">
Lorem, ipsum dolor
<div class="full_text">
<div>
Lorem, ipsum dolor sit amet consectetur adipisicing elit.
<button>X</button>
</div>
</div>
<a href="#" class="trigger">(...)</a>
</div>
我正在编写如下所示的 php 代码,其中我在特定字数限制后添加了 省略号 (...)。
<?php
$programs = array();
foreach ( $xml_files as $file ) {
$xml = simplexml_load_file($src_dir."/".$file) or die('Unable to load XML');
$path_title_en = $xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$path_description_en = $xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$programs[] = array( "episode_title" => (string)$path_title_en,
"description" => (string)$path_description_en;
}
$program["episode_title"] = substr($program["episode_title"],0,50).' <a href="">(...)</a>'; /* ellipsis is added after a particular word limit */
$program["description"] = substr($program["description"],0,100).' <a href="">(...)</a>'; /* ellipsis is added after a particular word limit */
?>
<table>
<tr>
<td style="width:8%; text-align:center;"><?php echo $program["episode_title"]; ?></td> /* Line A */
<td style="width:8%; text-align:center;"><?php echo $program["description"]; ?></td> /* Line B */
</tr>
</table>
行#A显示以下文字:
中的洪水问题
ABCSGSGSGSGSGSG 和
SHSHSGFASGXDS (...)
问题陈述:
我想知道我需要添加什么 JS 代码,以便在 单击 (...) 时,全文显示在模态中,例如 this .
您应该使用经过修改的演示才能在该模式中使用自定义文本。 https://www.w3schools.com/code/tryit.asp?filename=G4QNZITEFN72
然后修改您的代码,以便能够在该模式中发送全文 window
<?php
$programs = array();
foreach ( $xml_files as $file ) {
$xml = simplexml_load_file($src_dir."/".$file) or die('Unable to load XML');
$path_title_en = $xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$path_description_en = $xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$programs[] = array("episode_title" => (string) $path_title_en, "description" => (string)$path_description_en;);
}
foreach ( $programs as $program ) {
$episode_title = substr($program["episode_title"],0,50).' <a href="#show_full_title" onClick="showModal(\''.htmlspecialchars($program["episode_title"]).'\')">(...)</a>'; /* ellipsis is added after a particular word limit */
$description = $program["description"] = substr($program["description"],0,100).' <a href="#show_full_description" onClick="showModal(\''.htmlspecialchars($program["description"]).'\')">(...)</a>'; /* ellipsis is added after a particular word limit */
?>
<table>
<tr>
<td style="width:8%; text-align:center;"><?php echo $episode_title; ?></td> /* Line A */
<td style="width:8%; text-align:center;"><?php echo $description; ?></td> /* Line B */
</tr>
</table>
<?php } ?>
向该标签添加一个 onClick 处理程序,它将调用带全文的 showModal 函数。
我只是用模态 UI、脚本和少量逻辑来更新您的代码以将内容传递给模态。试试这个我希望它能帮助你。谢谢
var modal = document.getElementById("readMoreModal");
var btn = document.getElementsByClassName("readMoreModalTrigger")[0];
var closeBtn = document.getElementById("close");
// When the user clicks on <span> (x), close the modal
closeBtn.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Append Readmore content in modal
function readMoreMethod(text) {
document.getElementById("modal-content-append").innerHTML = text;
modal.style.display = "block";
}
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#close:hover,
#close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<?php
$programs = array();
foreach ( $xml_files as $file ) {
$xml = simplexml_load_file($src_dir."/".$file) or die('Unable to load XML');
$path_title_en = $xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$path_description_en = $xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$programs[] = array( "episode_title" => (string)$path_title_en,
"description" => (string)$path_description_en;
}
$program["episode_title"] = substr($program["episode_title"],0,50).' <a class="readMoreModalTrigger" href="JavaScript:Void(0);" onclick="readMoreMethod('$program["episode_title"]')">(...)</a>'; /* ellipsis is added after a particular word limit */
$program["description"] = substr($program["description"],0,100).' <a
class="readMoreModalTrigger" href="JavaScript:Void(0);" onclick="readMoreMethod('$program["description"]')">(...)</a>'; /* ellipsis is added after a particular word limit */
?>
<table>
<tr>
<td style="width:8%; text-align:center;"><?php echo $program["episode_title"]; ?><a class="readMoreModalTrigger" href="JavaScript:Void(0);" onclick="readMoreMethod('tadsad sadsad asdasd asdas dsad ')" href="">(...)</a></td>
<td style="width:8%; text-align:center;"><?php echo $program["description"]; ?></td>
</tr>
</table>
<!-- The Modal -->
<div id="readMoreModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="close">×</span>
<p id="modal-content-append"></p>
</div>
</div>
这是我对字符串提取的完全测试实现以及来自 w3schools 演示的所需模态功能:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
.triggersModal {
padding: 50px;
border: solid 2px black;
margin: 50px;
cursor: pointer;
}
/* The Modal (background) */
#myModal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#modalCloser {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#modalCloser:hover,
#modalCloser:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<?php
$episodes = [
[
'episode_title' => 'Lorem Ipsum',
'description' => "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."],
[
'episode_title' => "The standard 'Lorem Ipsum' passage, used since the 1500s",
'description' => '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
]
];
foreach ($episodes as $index => $episode) { ?>
<div class="triggersModal" data-index="<?php echo $index; ?>">
<div><?php
if (strlen($episode['episode_title']) <= 50) {
echo $episode['episode_title'];
} else {
echo substr($episode['episode_title'], 0, 50) , "(...)";
}
?></div>
<div><?php
if (strlen($episode['description']) <= 100) {
echo $episode['description'];
} else {
echo substr($episode['description'], 0, 100) , "(...)";
}
?></div>
</div>
<?php } ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="modalCloser">×</span>
<p id="modalFullTitle"></p>
<p id="modalFullDescription"></p>
</div>
</div>
<script>
// Transfer data from php to javascript
let episodes = <?php echo json_encode($episodes); ?>,
classname = document.getElementsByClassName("triggersModal"),
modal = document.getElementById("myModal");
// Bind value insertion and modal display to onclick event of every element with named class
for (let i = 0, len = classname.length; i < len; ++i) {
classname[i].onclick = function() {
let index = this.getAttribute('data-index');
document.getElementById("modalFullTitle").innerHTML = episodes[index]['episode_title'];
document.getElementById("modalFullDescription").innerHTML = episodes[index]['description'];
modal.style.display = "block";
}
}
// Close the modal
document.getElementById("modalCloser").onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
您需要用您的文件碎片替换我的硬编码输入(上方)。要创建 your $episodes
数组并使用单个循环显示主层的内容,请在 <body>
标记内使用它来显示可点击的阅读更多框:
<?php
$episodes = [];
$index = 0;
foreach ($xml_files as $file) {
$xml = simplexml_load_file("{$src_dir}/{$file}");
if (!$xml) {
continue;
}
$episode_title = (string)$xml->xpath('//StringAssetInfo[attrName="CASE_EPISODE_TITLE"]/value');
$description = (string)$xml->xpath('//TextAssetInfo[attrName="CASE_DESCRIPTION_ENGLISH"]/value');
$episodes[] = ['episode_title' => $episode_title, 'description' => $description]; // used downscript to deliver data to clientside/js
?>
<div class="triggersModal" data-index="<?php echo $index; ?>">
<div>
<?php
if (strlen($episode_title) <= 50) {
echo $episode_title;
} else {
echo substr($episode_title, 0, 50) , "(...)";
}
?>
</div>
<div>
<?php
if (strlen($description) <= 100) {
echo $description;
} else {
echo substr($description, 0, 100) , "(...)";
}
?>
</div>
</div>
<?php
++$index;
}
?>
注意事项:
- 所有点击事件都写在脚本块中,而不是在 html 中,以保持整洁和可读。
- 仅当字符串有足够的长度时才需要使用省略号。
- 使用
json_encode()
. 将数据从php传递给js
- 不要使用
die()
。 - 我的偏好是不命名只会使用一次的变量(在 php 或 js 中)。有一些例外,但这是我的默认哲学。
- 由于查找数组 (
episodes
) 是一个索引数组,从被单击的元素传递的唯一相关值是索引。data-
属性是维护主显示和要在模态中显示的数据之间的关系。 - 不推荐使用
<table>
标签显示 non-tabular 内容。我对页面和模态的样式所做的很少。我不想偏离您提供的演示太远。 - HTML 需要标识的元素应包含一个
id
以便于 javascript 定位。在多个位置出现的元素应包含class
. - 测试我的脚本后,在主页或模式中显示引用文本没有问题。
- 我试图保留语法 simple/readable,但我通常更喜欢 php 和 js 中的三元运算符(内联条件)。有些人在显示 php 时更喜欢 shorthand
<?=
和?>
。我对此也很满意;选择你喜欢的。 - 最后但并非最不重要的一点是,如果您的输入字符串来自不安全的渠道,或者如果它们包含 html,它会改进您的应用程序的 stability/security 编码 html 实体使用
htmlspecialchars($string, ENT_QUOTES, 'UTF-8')
显示在屏幕上的任何字符串( 在计算字符串长度之后,但在显示之前 )。这是一个很好的参考:
这是我的源代码转移到可运行的 Whosebug 片段:
// Transfer data from php to javascript
let lookup = [{"episode_title":"Lorem Ipsum","description":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},{"episode_title":"The standard 'Lorem Ipsum' passage, used since the 1500s","description":"\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\""}],
classname = document.getElementsByClassName("triggersModal"),
modal = document.getElementById("myModal");
// Bind value insertion and modal display to onclick event of every element with named class
for (let i = 0, len = classname.length; i < len; ++i) {
classname[i].onclick = function() {
let index = this.getAttribute('data-index');
document.getElementById("modalFullTitle").innerHTML = lookup[index]['episode_title'];
document.getElementById("modalFullDescription").innerHTML = lookup[index]['description'];
modal.style.display = "block";
}
}
// Close the modal
document.getElementById("modalCloser").onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
.triggersModal {
padding: 50px;
border: solid 2px black;
margin: 50px;
cursor: pointer;
}
/* The Modal (background) */
#myModal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#modalCloser {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#modalCloser:hover,
#modalCloser:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="triggersModal" data-index="0">
<div>Lorem Ipsum</div>
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the (...)</div>
</div>
<div class="triggersModal" data-index="1">
<div>The standard 'Lorem Ipsum' passage, used since the(...)</div>
<div>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore(...)</div>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="modalCloser">×</span>
<p id="modalFullTitle"></p>
<p id="modalFullDescription"></p>
</div>
</div>
</body>
</html>
已调整为单独显示单元格文本的另一个可运行片段...
// Transfer data from php to javascript
let lookup = [{"episode_title":"Lorem Ipsum","description":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},{"episode_title":"The standard 'Lorem Ipsum' passage, used since the 1500s","description":"\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\""}],
classname = document.getElementsByClassName("triggersModal"),
modal = document.getElementById("myModal");
// Bind value insertion and modal display to onclick event of every element with named class
for (let i = 0, len = classname.length; i < len; ++i) {
classname[i].onclick = function() {
let index = this.getAttribute('data-index'),
content = this.getAttribute('data-content');
document.getElementById("modalText").innerHTML = lookup[index][content];
modal.style.display = "block";
}
}
// Close the modal
document.getElementById("modalCloser").onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
.box {
padding: 50px;
border: solid 2px black;
margin: 50px;
}
.triggersModal {
cursor: pointer;
}
/* The Modal (background) */
#myModal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
#modalCloser {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
#modalCloser:hover,
#modalCloser:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="box">
<div class="triggersModal" data-index="0" data-content="episode_title">Lorem Ipsum</div>
<div class="triggersModal" data-index="0" data-content="description">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the (...)</div>
</div>
<div class="box">
<div class="triggersModal" data-index="1" data-content="episode_title">The standard 'Lorem Ipsum' passage, used since the(...)</div>
<div class="triggersModal" data-index="1" data-content="description">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore(...)</div>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="modalCloser">×</span>
<p id="modalText"></p>
</div>
</div>
</body>
</html>
这里是上述 php 执行的 pastebin 转储:https://pastebin.com/YnhNq6rD
这是给你的HTML/CSS/JS。
const trigger = document.querySelector(".trigger");
trigger.addEventListener("click", () => {
const fullTextSibling = trigger.previousElementSibling;
fullTextSibling.classList.add("active");
const closeModal = document.querySelector(".full_text > div > button");
closeModal.addEventListener("click", () => {
fullTextSibling.classList.remove("active");
});
});
.full_text {
display: none;
}
.full_text > div {
min-width: 300px;
min-height: 100px;
background: white;
padding: 20px;
border-radius: 10px;
}
.full_text.active {
display: flex;
background: #80808069;
width: 100%;
height: 100vh;
position: fixed;
top: 0;
align-items: center;
justify-content: center;
}
<div class="container">
Lorem, ipsum dolor
<div class="full_text">
<div>
Lorem, ipsum dolor sit amet consectetur adipisicing elit.
<button>X</button>
</div>
</div>
<a href="#" class="trigger">(...)</a>
</div>