簡體   English   中英

div 是否出現在帶有 jquery/javascript 的 TD 的 TD onclick 的右側?

[英]Have div appear to the right of a TD onclick of TD with jquery/javascript?

所以我有一個絕對定位的 5x5 像素正方形的 div。

如果我有一張桌子說

<table><tr><td>Something</td></tr></table>

當我單擊 TD 內的任何位置時,我希望 div 恰好顯示在 TD 的右側,因此無論我在 TD 中的哪個位置單擊,它都應該顯示在 TD 的右側。 有沒有一種簡單的方法可以在 Jquery/Javascript 中實現這一點?

我建議使用隱藏的table單元格,並在其中顯示div

<table>
    <tr>
        <td>Something</td>
        <td class="hidden"><div></div></td>
    </tr>
    <tr>
        <td>Something</td>
        <td class="hidden"><div></div></td>
    </tr>
</table>

jQuery:

$('tr td').click(
    function(){
        $(this).closest('tr').find('.hidden').toggle();
    });

CSS:

td {
    vertical-align: middle;
    width: 5em;
    height: 2em;
}

.hidden {
    display: none;
}

.hidden div {
    display: block;
    height: 5px;
    width: 5px;
    background-color: #f90;
}

JS小提琴


編輯對內容進行了一些修改,使包含的 ( .hidden ) td始終可見(以減少由於突然出現的表格單元格而導致頁面跳轉的機會):

jQuery:

 $('tr td').click( function() { $(this).closest('tr').find('.hidden div').toggle(); });

CSS:

 table { empty-cells: show; } td { vertical-align: middle; width: 5em; height: 2em; } td:hover { background-color: rgba(255,255,0,0.2); }.hidden div { display: none; }.hidden div { height: 5px; width: 5px; background-color: #f90; }

JS小提琴


根據@Nicky Waite 的建議進行編輯(如下):

也許將您的 hover 貼在 tr 元素上。

$('tr').click(

function() {
    $(this).find('.hidden div').toggle();
});

JS 小提琴演示

給TD相對position。 並將 div 放入其中。 給你的 div

right:0px;

點擊

給你的 div 風格:

left:50%;
margin-left:-2px //(these might need to be change a bit)

Select 在使用 jQuery 選擇器(使用 class 或 id)之后要放置<td> <td> <td>,並使用 $.append()

以下是您選擇 jQuery 標簽的選項

http://api.jquery.com/category/selectors/

所以像

$("td").click(function(event) {
     $(this).append("<td></td>");
});

是的,您可以通過幾種方式處理它。 這里有一個想法:

$("td").click(function(e) {
  el = $(e.target);
  el.after("<div class='my_square' />");
  sq = $(el + " + .my_square");
  sq.css({
    position: "absolute",
    left: el.offset().left,
    top: el.offset().top + el.outerHeight() / 2
  })
})

這是使用職位的另一種解決方案。 雖然我不確定你是想要多個盒子還是只想要一個。

http://jsfiddle.net/nickywaites/DvTBR/

$(function() {

$('#summary td').click(function() {

    var td = $(this);
    var position = td.position();
    $('#link').css({
        top: position.top + (td.height() / 2),
        left: position.left + td.width() + 10
    }).show();

});

});

<div id="link"></div>
<table id="summary">
<tr><td>Toast</td></tr>
<tr><td>Toast</td></tr>
</table>

#link {
width:5px;
height:5px;
background-color:royalblue;
display:none;  
position:absolute;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM