一个高度固定的div里面有好几个p标签 当p标签过多超出div的高度时,让超出的元素隐藏,同时让div最底部显示省略号 ,如果没有超出,就不显示省略号 请你给出五种写法
时间: 2023-06-12 20:08:12 浏览: 52
1. 使用CSS3中的text-overflow属性
```css
div {
height: 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
```
2. 使用JavaScript计算高度并设置样式
```html
<div id="myDiv">
<p>...</p>
<p>...</p>
<p>...</p>
...
</div>
```
```css
#myDiv {
height: 100px;
overflow: hidden;
}
```
```javascript
const div = document.getElementById('myDiv');
const p = div.getElementsByTagName('p');
let totalHeight = 0;
for (let i = 0; i < p.length; i++) {
totalHeight += p[i].offsetHeight;
}
if (totalHeight > div.offsetHeight) {
div.style.height = div.offsetHeight + 'px';
div.style.overflow = 'hidden';
div.style.textOverflow = 'ellipsis';
div.style.whiteSpace = 'nowrap';
p[p.length - 1].style.display = 'none';
const span = document.createElement('span');
span.innerHTML = '...';
div.appendChild(span);
}
```
3. 使用jQuery计算高度并设置样式
```html
<div id="myDiv">
<p>...</p>
<p>...</p>
<p>...</p>
...
</div>
```
```css
#myDiv {
height: 100px;
overflow: hidden;
}
```
```javascript
const div = $('#myDiv');
const p = div.find('p');
let totalHeight = 0;
p.each(function() {
totalHeight += $(this).outerHeight(true);
});
if (totalHeight > div.height()) {
div.css({
height: div.height(),
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
});
p.last().hide();
const span = $('<span>...</span>');
div.append(span);
}
```
4. 使用Vue.js计算高度并设置样式
```vue
<template>
<div ref="myDiv">
<p>...</p>
<p>...</p>
<p>...</p>
...
</div>
</template>
<script>
export default {
mounted() {
const div = this.$refs.myDiv;
const p = div.getElementsByTagName('p');
let totalHeight = 0;
for (let i = 0; i < p.length; i++) {
totalHeight += p[i].offsetHeight;
}
if (totalHeight > div.offsetHeight) {
div.style.height = div.offsetHeight + 'px';
div.style.overflow = 'hidden';
div.style.textOverflow = 'ellipsis';
div.style.whiteSpace = 'nowrap';
p[p.length - 1].style.display = 'none';
const span = document.createElement('span');
span.innerHTML = '...';
div.appendChild(span);
}
}
}
</script>
```
5. 使用React计算高度并设置样式
```jsx
import React, { useEffect, useRef } from 'react';
export default function MyComponent() {
const divRef = useRef(null);
useEffect(() => {
const div = divRef.current;
const p = div.getElementsByTagName('p');
let totalHeight = 0;
for (let i = 0; i < p.length; i++) {
totalHeight += p[i].offsetHeight;
}
if (totalHeight > div.offsetHeight) {
div.style.height = div.offsetHeight + 'px';
div.style.overflow = 'hidden';
div.style.textOverflow = 'ellipsis';
div.style.whiteSpace = 'nowrap';
p[p.length - 1].style.display = 'none';
const span = document.createElement('span');
span.innerHTML = '...';
div.appendChild(span);
}
}, []);
return (
<div ref={divRef}>
<p>...</p>
<p>...</p>
<p>...</p>
...
</div>
);
}
```