jquery - CSS/jQuery - 悬停时图像上的文本

标签 jquery html css hover mako

我有一个悬停功能,当悬停在图像上时,文本会放在图像下方。但我希望文字位于图像之上。这样我们您将鼠标悬停在图像上会淡出一点并显示文本。

像这样:
Hover Hover2

谁能帮帮我?

这是 jQuery:

<%def name="javascript()">

<script type="text/javascript">

    $(document).ready(function () {
       $('.category-box').each(function () {
           var hovertext = $(this).find('.hovertext').html();
           var hoverbox = $('<div id="hoverbox">' + hovertext + '</div>').css({
               'position': 'absolute',
               'top': $(this).css('top'),
               'left': $(this).css('left'),
               'width': $(this).css('width'),
               'background-color': '#f0f0f0',
               'z-index': 1000,
               'border-radius': '5px',
               '-moz-border-radius': '5px',
               '-webkit-border-radius': '5px',
               'display': 'none',
               'cursor': 'pointer'
           });

           $(this).find('h4').after(hoverbox);

           $(this).hover(function () {
               hoverbox.fadeIn('fast');
           }, function () {
               hoverbox.fadeOut('fast');
           });

           $(this).not('#mitp').click(function () {
               location.href = '${request.route_url('
               new_case ', category='
               ')}' + $(this).find('h4').html();
           });
       });

       $('#mitp').click(function () {
           location.href = '${request.route_url('
           mitp ')}';
       });
   });

魔晄:

% if categories:

% for category in categories:
    <div class="category-box">
        <img src="/category_icon/${category['id']}" width="120" height="120" />
        <h4>${category['name']}</h4>
        <span class="hovertext">
        % if category['description'] != '.':
            ${h.literal(category['description'])}
        % endif
        </span>
    </div>
% endfor
% endif

还有 CSS:

.category-box {
    float: left;
    margin: 15px 10px 5px 10px;
    text-align: center;
    width: 120px;
    min-height: 120px;
    cursor: pointer;
}

.category-box:hover {
    cursor: pointer;
    background-color: #f0f0f0;
    border-radius: 5px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
}

.hovertext {
    text-align: center;
    display: none;
}

最佳答案

您的代码存在一些问题:

  1. 您正在使用 <div id="hoverbox">用于插入多个元素,但这意味着您的文档中有重复的 ID,这不是有效的 html
  2. .category-box应该有 position: relative;您可以使用 position: absolute 正确定位子元素
  3. 根据以上几点,您可以简单地添加'top': 0, 'left': 0,给你的hoverbox

在您的代码中 $(this).css('top')将简单地返回值 auto这在这里没有影响。


Example

关于jquery - CSS/jQuery - 悬停时图像上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39101524/

相关文章:

html - 在 P 标签上应用 css linear-gradient 以不同的方式设置每一行的样式

html - 如何仅使用 CSS 设置 <select> 下拉菜单的样式?

jquery - 在 MVC 布局 View 中加载 jQuery 的正确位置

php - 表单提交停止显示 JSON 对象

javascript - autoNumeric 不允许从数字键盘/Internet Explorer 输入十进制

javascript - 如何确定在 Javascript 的父级中单击了哪个子图像

Javascript 在加载时显示 div

javascript - 窗口失焦时恢复选项

html - 通过 http 提供 HTML5 视频

html - 绝对和相对定位