2016-04-06 21 views
0
/* css for button to change size on click */ 
.button:focus { 
    width: 99%; 
    height: 500px; 
    } 

//below is the script that handles the auto scroll to the button clicked on screen. 
    $(document).ready(function() { 
$('.button').click(function() { 
    $('html,body').animate({ scrollTop: $(this).offset().top - (($(window).height()/1.5) - $(this).outerHeight(true))/2 }, 2000); 
    $(this).empty(); //empty title and author to prepare for recipe 
     $(this).append("Recipe Instructions Below"); 

}); 
}); 

在一個網站我建設我拉添加到數據庫中的最新信息,並在一個按鈕,可點擊顯示每一行。我的目標是按鈕的大小約爲100px×60px,點擊「聚焦」將會增加到屏幕寬度。添加元素的狀態改變按鈕的Html

現在,當我點擊按鈕時,我想清空按鈕並用數據庫中的更多信息替換它,即點擊配方的說明。當我隨後忽略或點擊按鈕時,我希望它恢復到原來的狀態,只顯示食譜名稱和作者。

我在看這個的方式是按鈕是對象,但我認爲這是非常錯誤的。如果可能的話,任何人都可以給我任何反饋,以便更智能和更有效的方式來解決這個問題,因爲我唯一的問題是單擊時向按鈕添加更多元素。我真的很感激任何反饋。

這裏是一個小的演示https://jsfiddle.net/DxKoz/twj7m2sb/1/

回答

1

這應該做的事。

$(document).ready(function() { 
    $('.button').click(function() { 
    var btn = $(this); 
    $('html,body').animate({ 
     scrollTop: $(this).offset().top - (($(window).height()/1.5) - $(this).outerHeight(true))/2 

    }, 2000, 
    function() { 
     btn.html("Recipe Instructions Below"); //html() so you don't have to use empty() 
    }); 

}); 

如果您有更多的按鈕來添加,然後用for循環,名稱使用id =循環次數每個按鈕。例如:

for(var i=1; i<buttons.length; i++) { 
    $('#buttons-list').append('<button id="' + i + '">' + Recipe Name + Author Name + '</button>'); 
} 

$('button').click(function() { 
    var button_nr = $(this).id; 
    $('#'+button_nr).html("Recipe Instructions Bellow"); //html() so you don't have to use empty() 
}); 

使用var button_nr = $(this).id您可以在陣列和使用button_nr打印它獲得按鈕號碼,然後,例如,保存食譜。

0

我不會用空。相反,在按鈕類中有兩個DIV,並根據您按鈕的活動狀態切換其可見性,使用和模糊事件。由於您使用jQuery,您可以使用兒童()爲目標的按鈕中的類(如果你有一個以上的頁面,將不會觸發所有的人都在。)

https://jsfiddle.net/jzuegnkx/1/

HTML:

<body> 
<button class="button"> 
    <div class="title"> 
    Recipe name<br /> 
    By: Author 
    </div> 
    <div class="details"> 
    Recipe Details 
    </div> 
</button> 
</body> 

CSS:

我只加一個班,默認的細節顯示:無。

.details { 
    display: none; 
} 

的Javascript:

$(document).ready(function() { 
    $('.button').click(function() { 
    $('html,body').animate({ scrollTop: $(this).offset().top - (($(window).height()/1.5) - $(this).outerHeight(true))/2 }, 2000); 
     //$(this).empty(); //empty title and author to prepare for recipe. 
     //$(this).append("Recipe Instructions Below"); 
    $(this).children('.title').hide(); 
    $(this).children('.details').show(); 
    }); 
    $('.button').blur(function() { 
    $(this).children('.details').hide(); 
    $(this).children('.title').show(); 
    }); 
}); 
+0

哇,太感謝你了。對於我來說,這是一個完美的方法,以便顯示和隱藏我從數據庫onclick中獲取的信息。非常感謝你。 – Nathan