【发布时间】:2016-10-19 11:04:25
【问题描述】:
我有什么:
- 带有 ID、姓名、职位、部门和地址的 JSON。
- 同样的 JSON 有超过 1000 名随机员工循环到一个表中。
- 每个人都有一个自定义属性 (user_id) 和相同的 CSS 类用于悬停。
- 当鼠标悬停在一名员工身上时,一个隐藏的准备好的和样式化的 div 用于提供信息。
我需要什么:
- 当我将鼠标悬停在某个员工上时,我需要显示所有员工信息,例如姓名、职位、部门和地址。请记住,悬停是有效的,但信息仍然是静态的。所以基本上,我的逻辑是自定义 attr user_id 和 JSON id 匹配 = 填充 html。 我该怎么做?
var xmlhttp = new XMLHttpRequest();
var url = "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/189576/1743369/lDhMee0RoA1IO5D/generated.json";
var employees;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
employees = JSON.parse(this.responseText);
write(employees);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function write(arr) {
var i;
var out = '<table>';
for(i = 0; i < arr.length; i++) {
out += '<tr>';
out += '<td class="hoverKartX" user_id="' + arr[i].id + '">' + arr[i].name + '</td>';
out += '<td>' + arr[i].position + '</td>';
out += '</tr>';
}
out += '</table>';
document.getElementById('employees').innerHTML = out;
}
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('.hoverKartX').hover(function(e) {
//$(this).parent().find(".hoverKart").show();
$(".hoverKart").show();
}, function() {
$('.hoverKart').hide();
});
$('.hoverKartX').mousemove(function(e) {
$(".hoverKart").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
// preventing 'falling' to the right on smaller screen
if ($(".hoverKart").position()['left'] + $('.hoverKart').width() > $(window).width()) {
$(".hoverKart").css("left", $(window).width() - $(".hoverKart").width());
};
// preventing 'falling from the bottom of the page'
if ((e.pageY + moveDown + $(".hoverKart").height()) > ($(window).scrollTop() + $(window).height())) {
$(".hoverKart").css("top", $(window).height() - $(".hoverKart").height() + $(window).scrollTop());
}
});
});
.hoverKart {
position: absolute;
width: 400px;
height: 220px;
border-radius: 25px;
border: 1px solid #999;
z-index: 1;
display: none;
background: #fff;
}
<!-- hidden div-->
<div class="hoverKart">
<div class="container">
<div class="cardTop"><p><!-- JSON DATA (ID) --></p></div>
<div class="imgHolder">
<img class="employee" src="img/img.jpg" alt="employee image">
<img class="eLogo" src="img/logo.jpg" alt="logo">
</div>
<div class="eInformation">
<p class="eName"><!-- JSON DATA (NAME) --></p>
<p class="ePos"><!-- JSON DATA (DEPARTMENT) --></p>
<div class="eDep">
<img src="img/icons-dep/5.png" alt="department logo">
</div>
<p class="eOp">Operations</p>
<p class="eOp2"><!-- JSON DATA (ADDRESS) --></p>
</div>
</div>
</div>
<div id="employees"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
【问题讨论】:
-
你可以查看我的答案。我为您的代码创建了一个工作小提琴。
标签: javascript jquery json