从html中的文本文件中读取图像源路径

问题描述 投票:0回答:4

我必须以幻灯片形式显示一系列图像。我将在文本文件中拥有图像的路径。如何从文本文件中读取图像路径?现在我有一个硬编码的代码如下:

<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

javascript html
4个回答
1
投票

最简单的方法可能是将您的网址存储在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);
});

1
投票

首先你必须明白单独的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%'>";
}

1
投票

关于我的评论,你请求一个URL,然后解析响应并使用HTML而不是使用Javascript做一些事情。

我们首先等待加载文档。

  • 加载文档后,我们等待按钮单击。
  • 单击按钮时,我们获取一个URL,在您的情况下是一个http://example.com/file.txt文本文件。
  • 然后我们使用response.text()来获取正文,现在我们可以用它做一些事情,比如将结果添加到结果div。

获取文档: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>

-1
投票

HTML本身不可能做到这一点,但你可以用CSS或JavaScript来做到这一点。

在CSS中,您可以添加鼠标悬停/鼠标单击以使用不透明度或使用翻译方式显示另一个图像。

在JavaScript中,您可以做更多事情。

也许这会帮助你:http://css3.bradshawenterprises.com/cfimg/

© www.soinside.com 2019 - 2024. All rights reserved.