使用省略号截断文本也会截断工具提示

时间:2013-10-29 02:37:03

标签: javascript jquery html css

我使用省略号截断文本并在工具提示中显示整个文本。如果文本溢出,则仅显示工具提示。 工具提示在Chrome中看起来不错,但在IE和Firefox中却没有。在IE中,工具提示文本也被截断,在firefox中,工具提示本身被剪切。

<div class="card">
    <p>From:</p>
    <p> Dark Angel </p>
    <p class="ellipsis"> QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQAAAAAA
        New york, US<p>        
<div>

CSS:

.card {
    height:416px;
    width:280px;
    display:block;
    border: 1px solid black;
}

.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
}

jQuery的:

$('p.ellipsis').bind('mouseenter', function () {
    var $this = $(this);

    if (this.offsetWidth < this.scrollWidth && !$this.attr('title'))
        $this.attr('title', $this.text());

1 个答案:

答案 0 :(得分:0)

您可以给元素一个不同的类名,然后使用Javascript对其进行更新,设置相关的ellipsis类名,以及在那时捕获文本并将其存储为元素的数据属性。 ,因此您以后可以访问它。

请注意,我将<p>标记更改为具有类名pre-ellipsis ...

// add a data-title attribute with the original text, then modify the class list
// to remove pre-ellipsis and add ellipsis

$("p.pre-ellipsis").each(function() {
    var $this = $(this);
    $this.data("title", $this.text());
    $this.removeClass("pre-ellipsis").addClass("ellipsis");
});

// your original code, but modified to get the tooltip text from the data attribute
$("p.ellipsis").on("mouseenter", function () {
    var $this = $(this);
    if (this.offsetWidth < this.scrollWidth && !$this.attr('title')) {
        $this.attr('title', $this.data("title"));
    }
});
.card {
    height:416px;
    width:280px;
    display:block;
    border: 1px solid black;
}

.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="card">
<p>From:</p>
<p> Dark Angel </p>
<p class="pre-ellipsis"> QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQAAAAAA
New york, US<p>        
<div>