简体   繁体   中英

HTML & JavaScript How to Make nth Lines of Text Appear with nth Number of Clicks?

I am very new to html and JavaScript, but I am an advanced novice at understanding programming. I am looking for a way to make nth lines of text appear on nth button clicks of a button and when there are no more text lines to show the button does nothing. I imagine that there should be some index to keep track of the amount of clicks and a way to pass a number of clicks that should occur to some function, but I am having trouble finding anything. Can someone point me in the right direction or demonstrate the basics of what I must do. Here is a visual demo of what I want to happen on the webpage:

Click This

Click This
this line appears on first click

Click This
this line appears on first click
this line appears on second click

Click This
this line appears on first click
this line appears on second click
...
this line appears on nth click

Here is some code that does a bit what I am expecting. Is there any changes I can make to make it work more generally?

 $(function() { $("#visible").click(function() { if (typeof this.counter == 'undefined') { this.counter = 0; } $('#invisible' + this.counter).toggleClass("show"); ++this.counter; }); });
 .hide { display: none; } .show { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id="visible">Click This</p> <p id="invisible0" class="hide">this line appears on the first click</p> <p id="invisible1" class="hide">this line appears on the second click</p> <p id="invisible2" class="hide">this line appears on the third click</p>

Thanks in advance,
Vectorjon

This might not be optimal, but at least it's something you can start with. Basically I set the font-size (in this case 12px) and then added that height + 2px (14px) to the size of the div container.

https://jsfiddle.net/hassench/r7cgjzus/9/

 var expand = () => { $('.expandable').css('height', $('.expandable').height() + 14); }
 .expandable { font-size: 12px; height: 15px; overflow: hidden; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='expandable' onclick='expand()'> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam libero ex, vehicula id egestas sed, iaculis vel enim. Curabitur interdum sollicitudin turpis, sit amet semper magna rutrum pharetra. Donec blandit, enim at volutpat feugiat, nunc orci placerat nunc, eu placerat tortor libero nec est. Aliquam erat volutpat. Ut dapibus tellus metus, a lacinia risus gravida quis. Nullam placerat maximus risus ut tristique. Mauris rhoncus sagittis erat, eget mollis ligula. Nulla accumsan fermentum dictum. </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM