html+js+css做一个鼠标碰到文字,下面会显示9张图片,并且会根据坐标显示直到碰到下一个文字,否则一直显示该文字的图片
时间: 2024-03-17 13:46:42 浏览: 13
好的,这是一个比较有趣的问题,让我们来一步一步实现这个功能吧:
首先,我们需要在 HTML 中定义一些文本和图片元素,如下所示:
```html
<p>这是一段文本,当你将鼠标悬停在这个词上时,下面将显示一些图片。</p>
<div id="image-container"></div>
```
其中,`<p>` 元素中的文本可以根据实际情况进行修改,而 `<div>` 元素用于显示图片。
接下来,我们需要编写一些 CSS 样式来控制页面的布局和样式。这里我们使用 flexbox 布局来将图片水平排列,并且设置一些样式使得图片始终在页面底部。
```css
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
}
p {
font-size: 24px;
line-height: 1.5;
text-align: center;
margin: 0 0 24px;
}
#image-container {
display: flex;
justify-content: center;
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 120px;
padding: 16px;
background-color: #fff;
box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.2);
overflow-x: auto;
overflow-y: hidden;
white-space: nowrap;
}
img {
width: 100px;
height: 100px;
margin: 0 8px;
object-fit: cover;
border-radius: 8px;
}
```
最后,我们需要编写一些 JavaScript 代码来实现鼠标悬停时显示图片的功能。具体来说,我们需要监听 `<p>` 元素中的单词,当鼠标悬停在单词上时,从服务器获取对应的图片并显示在 `<div>` 元素中。由于获取图片需要一定的时间,我们需要使用 debounce 函数来减少不必要的请求。
```javascript
const imageContainer = document.getElementById("image-container");
const words = Array.from(document.getElementsByTagName("p")[0].childNodes)
.filter((node) => node.nodeType === Node.TEXT_NODE)
.map((node) => node.textContent.trim().split(" "))
.reduce((acc, val) => acc.concat(val), []);
let currentWord = null;
const getImage = async (word) => {
const response = await fetch(`https://source.unsplash.com/featured/?${word}`);
const imageUrl = response.url;
return imageUrl;
};
const debounce = (func, wait) => {
let timeout;
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
};
const handleMouseEnter = debounce(async (event) => {
const word = event.target.textContent.trim();
if (word === currentWord) {
return;
}
currentWord = word;
const imageUrl = await getImage(word);
const imageElement = document.createElement("img");
imageElement.src = imageUrl;
imageContainer.innerHTML = "";
imageContainer.appendChild(imageElement);
}, 500);
words.forEach((word) => {
const textNode = document.createTextNode(` ${word} `);
const spanElement = document.createElement("span");
spanElement.appendChild(textNode);
spanElement.addEventListener("mouseenter", handleMouseEnter);
document.getElementsByTagName("p")[0].replaceChild(spanElement, textNode);
});
```
这样,我们就完成了整个功能的实现。当鼠标悬停在某个单词上时,页面下方会显示对应的图片,直到鼠标移动到下一个单词。如果没有下一个单词,那么将一直显示该单词的图片。