如何使用JavaScript根据API返回值修改CSS样式并实现条件渲染元素
Solution: Conditional NSFW Label & Image Blur Based on API Response
Let's adjust your code to implement the conditional logic you need. The key is to check the x_restrict value from each artwork object in the API response, then dynamically build the card HTML with the right elements and styles.
Modified JavaScript Code
First, let's rewrite the fetchData function to include the conditional checks:
const url = 'https://api.adoreanime.com/api/pixiv/?type=member_illust&id=12540747&page=1'; function fetchData(url) { fetch(url) .then((response) => response.json()) .then(function(data) { const cards = data.illusts.slice(0, 6).map((art) => { const imgSrc = art.image_urls.medium.replace('i.pximg.net', 'i.pixiv.cat'); // Check if x_restrict equals 1 const isNsfw = art.x_restrict === 1; // Build image container with conditional blur style const cardImage = ` <div class="card__image" style="${isNsfw ? 'filter: blur(10px)' : ''}"> <a href="https://www.pixiv.net/en/artworks/${art.id}" target="_blank" rel="noopener noreferrer"> <img src="${imgSrc}" alt="image"> </a> </div> `; // Add NSFW label only if restricted const nsfwTitle = isNsfw ? '<span class="card__title">NSFW</span>' : ''; // Combine all parts into a single card return ` <div class="card"> ${cardImage} ${nsfwTitle} </div> `; }); // Insert all generated cards into the wrapper const cardWrapper = document.querySelector('.card__wrapper'); cardWrapper.innerHTML = cards.join(''); }); } fetchData(url);
Key Changes Explained
- Conditional Blur Styling: We use a ternary operator to inject the
filter: blur(10px)inline style into thecard__imagediv only whenart.x_restrictis 1. If not, the style is omitted, falling back to your CSS default offilter: blur(0px). - Conditional NSFW Label: The
card__titlespan is only included in the HTML string if the artwork is marked as restricted (isNsfwis true). - Cleaner Array Handling: Replaced the indexed array + counter approach with
map()to directly generate an array of card HTML strings—this is more readable and maintainable. - Modern DOM Selection: Swapped
getElementsByClassName('card__wrapper')[0]fordocument.querySelector('.card__wrapper')for simpler, more concise DOM targeting.
CSS & HTML Remain Mostly Unchanged
Your existing CSS and HTML don't need major tweaks. Just keep the default card__image filter style in place (it will be overridden by inline styles when needed):
/* Existing CSS stays the same, ensure this line is present */ .card__image { filter: blur(0px); }
<section> <main class="card__wrapper"> </main> </section>
This setup ensures each card renders exactly as required: blurred with an NSFW label when x_restrict is 1, and normal otherwise.
内容的提问来源于stack exchange,提问作者TravelWhere
相关产品推荐
相关产品推荐

