如何使用jQuery将div宽度从50改为100%并返回

时间:2013-11-02 13:46:04

标签: javascript jquery html onclick width

我正在测试网站上工作(我正在学习html + css),现在我需要你的帮助。

我有3个带有文本的div(每个宽度为50%),并且在每个div的左上角我想要带有“+”符号的图像。当用户单击时,符号+将自身更改为 - 和div的宽度(仅适用于该div)。

好的例子就在这里:http://i39.tinypic.com/9va7pz.png(但我也想要“ - ”符号)

有人能告诉我该怎么做吗?我没有机会使用JS(新手)。

当然,如果可以对其进行动画处理(不仅仅是改变宽度)

(因为英语不好 - 希望你能理解我想要的东西)

3 个答案:

答案 0 :(得分:0)

    html:

        <div id='symbol'>+</div> // the "+" symbol, you'd like to click, you can change the + to a image.
        <div id='d1'></div>
        <div id='d2'></div>
        <div id='d3'></div>

js(with jquery):
    $('#symbol').click(function(){
       $(this).attr('id', 'sub')
       $(this).text('-') //if it's image, change the image
       $('#d1').css('width', '100%')
    });

   $('#sub').click(function(){
  $(this).attr('id', 'symbol')
       $(this).text('+') //if it's image, change back to "+" image
       $('#d1').css('width', '50%')
});

答案 1 :(得分:0)

据我所知,您的HTML应该是这样的

<div><span class='changeSign'>+</span>some text here</div>
<div><span class='changeSign'>+</span>some text here</div>
<div><span class='changeSign'>+</span>some text here</div>

然后你可以在你的

中定位你的位置:亲戚

你的jQuery就像这样

$(document).ready(function(){
   $('span.changeSign').click(function(){
if ($(this).text() == '+'){
$(this).parent('div').css('width','100%');
    $(this).text('-');
}     else {
$(this).parent('div').css('width','50%');
    $(this).text('+');
}    

   });
});

wodking例子 - http://jsfiddle.net/ncXvM/

答案 2 :(得分:0)

如果你只想简单地折叠 - 展开<div>,我认为这样做。

HTML:

<div class="collapse"><a>+</a><p>Some text...</p></div>

jQuery的:

$('a').click(function(){
    if($(this).parent('div').attr('class') == 'collapse'){
        $(this).text('-')//if it's an image, replace it via .attr('src', 'url');
        .parent('div').width('100%').attr('class','expand')
    }else {
        $(this).text('+').parent('div').width('50%').attr('class','collapse')
    }   
});

如果您想添加一些动画,只需将CSS transition添加到<div>

div { transition: width 0.5s linear;}

或使用jQuery .animate()

.animate({width:'100%'},500);