我必须以幻灯片形式显示一系列图像。我将在文本文件中拥有图像的路径。如何从文本文件中读取图像路径?现在我有一个硬编码的代码如下:
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="img_nature_wide.jpg" style="width:100%">
<div class="text">Caption Text</div>
</div>
带图像路径的示例文本文件:
https://res.cloudinary.com/demo/image/upload/sample.jpg https://res.cloudinary.com/demo/image/upload/v1/folder1/folder2/sample.jpg
最简单的方法可能是将您的网址存储在JSON
编码文件中,并使用fetch
来检索它。
想象一下,您的服务器中有以下JSON
文件:
"[
"https://placekitten.com/408/287",
"https://placekitten.com/200/286",
"https://placekitten.com/200/139"
]"
您可以使用fetch
检索文件,并使用生成的array
网址进行操作,以填充幻灯片:
fetch('http://example.com/yourFile.json')
.then(function(response){
// parse the fetch response
return response.json();
})
.then(function(myJson){
// do whatever you need with the image paths array...
console.log(myJson);
});
首先你必须明白单独的javascript无法访问你服务器中的其他文件总是需要php天气你实现ajax或不是所以这是一个PHP示例,因为你有一个文本文件urls.txt
与以下内容
https://res.cloudinary.com/demo/image/upload/sample.jpg https://res.cloudinary.com/demo/image/upload/v1/folder1/folder2/sample.jpg
//Get the contents of the text file
$text = file_get_contents("path/to/urls.txt");
//Split them by the seperate lines
$textArr = explode("\n",$text);
//loop through the array
for($i = 0; $i < count($textArr); $i++){
//Echo the images
echo "<img src='" . $textArr[$i] . "' style='width:100%'>";
}
关于我的评论,你请求一个URL,然后解析响应并使用HTML而不是使用Javascript做一些事情。
我们首先等待加载文档。
获取文档:Fetch
// When document is loaded and ready
$(document).ready(function(){
// On button click initiate
$("button").click(function(){
// Request URL, change to http://example.com/file.txt
fetch('https://api.ipify.org?format=json')
.then(response => response.text())
.then(data => {
// Log body text
console.log(data);
// Set #results text to body text
$('#results').text(data);
})
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="results"></div>
<button>Get External Content</button>
</body>
</html>
HTML本身不可能做到这一点,但你可以用CSS或JavaScript来做到这一点。
在CSS中,您可以添加鼠标悬停/鼠标单击以使用不透明度或使用翻译方式显示另一个图像。
在JavaScript中,您可以做更多事情。