You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery在网页中实现类Quora的富文本回答输入框?

Got it, building a Quora-style answer editor with those formatting features using jQuery is totally straightforward. Let's walk through this step by step—from setting up the HTML structure, to adding the jQuery logic for each formatting action, and even styling it to match Quora's clean, minimal look.


1. HTML Structure

First, we'll create a toolbar with buttons for each formatting option, paired with a textarea for answer input. This mirrors Quora's simple, functional layout:

<div class="answer-editor">
  <!-- Formatting Toolbar -->
  <div class="editor-toolbar">
    <button class="toolbar-btn" data-action="bold">B</button>
    <button class="toolbar-btn" data-action="italic">I</button>
    <button class="toolbar-btn" data-action="list">•</button>
    <button class="toolbar-btn" data-action="image">🖼️</button>
    <button class="toolbar-btn" data-action="link">🔗</button>
  </div>
  <!-- Answer Input Box -->
  <textarea id="answer-input" placeholder="Write your answer here..." rows="10"></textarea>
</div>
2. jQuery Logic

Next, we'll add the jQuery code to handle each formatting action. The core idea is to either wrap selected text in Markdown syntax or insert syntax snippets where the cursor is.

First, let's create helper functions to handle text selection and replacement in the textarea—this will make our code cleaner:

// Get selected text and its position in the textarea
function getTextareaSelection($textarea) {
  const start = $textarea[0].selectionStart;
  const end = $textarea[0].selectionEnd;
  const selectedText = $textarea.val().substring(start, end);
  
  return { start, end, text: selectedText };
}

// Replace selected text with new content and reposition the cursor
function replaceTextareaSelection($textarea, newContent) {
  const selection = getTextareaSelection($textarea);
  const fullText = $textarea.val();
  const updatedText = fullText.substring(0, selection.start) + newContent + fullText.substring(selection.end);
  
  $textarea.val(updatedText);
  
  // Move cursor to the end of the inserted content
  const newCursorPos = selection.start + newContent.length;
  $textarea[0].selectionStart = newCursorPos;
  $textarea[0].selectionEnd = newCursorPos;
  $textarea.focus();
}

Now let's add click handlers for each toolbar button:

$(document).ready(function() {
  // Bold formatting
  $('.toolbar-btn[data-action="bold"]').click(function() {
    const $input = $('#answer-input');
    const selection = getTextareaSelection($input);
    
    if (selection.text) {
      replaceTextareaSelection($input, `**${selection.text}**`);
    } else {
      // Insert empty bold syntax and place cursor in the middle
      replaceTextareaSelection($input, '** **');
      $input[0].selectionStart = selection.start + 2;
      $input[0].selectionEnd = selection.start + 2;
    }
  });

  // Italic formatting
  $('.toolbar-btn[data-action="italic"]').click(function() {
    const $input = $('#answer-input');
    const selection = getTextareaSelection($input);
    
    if (selection.text) {
      replaceTextareaSelection($input, `*${selection.text}*`);
    } else {
      replaceTextareaSelection($input, '* *');
      $input[0].selectionStart = selection.start + 1;
      $input[0].selectionEnd = selection.start + 1;
    }
  });

  // Bullet list formatting
  $('.toolbar-btn[data-action="list"]').click(function() {
    const $input = $('#answer-input');
    const selection = getTextareaSelection($input);
    
    if (selection.text) {
      // Add bullet point to every selected line
      const lines = selection.text.split('\n');
      const formattedLines = lines.map(line => `- ${line}`).join('\n');
      replaceTextareaSelection($input, formattedLines);
    } else {
      // Add bullet point to the current line
      const text = $input.val();
      let start = selection.start;
      // Move cursor to the start of the current line
      while (start > 0 && text[start - 1] !== '\n') start--;
      
      const updatedText = text.substring(0, start) + '- ' + text.substring(start);
      $input.val(updatedText);
      $input[0].selectionStart = start + 2;
      $input[0].selectionEnd = start + 2;
      $input.focus();
    }
  });

  // Insert image
  $('.toolbar-btn[data-action="image"]').click(function() {
    const $input = $('#answer-input');
    const altText = prompt('Enter image description (alt text):');
    if (!altText) return;
    
    const imageUrl = prompt('Enter image URL:');
    if (!imageUrl) return;
    
    const markdown = `![${altText}](${imageUrl})`;
    replaceTextareaSelection($input, markdown);
  });

  // Insert link
  $('.toolbar-btn[data-action="link"]').click(function() {
    const $input = $('#answer-input');
    const linkText = prompt('Enter link text:');
    if (!linkText) return;
    
    const linkUrl = prompt('Enter link URL:');
    if (!linkUrl) return;
    
    const markdown = `[${linkText}](${linkUrl})`;
    replaceTextareaSelection($input, markdown);
  });
});
3. Styling (Quora-Inspired)

To make it look like Quora's answer box, add this CSS for a clean, minimal style:

.answer-editor {
  max-width: 800px;
  margin: 20px auto;
  font-family: 'Arial', sans-serif;
}

.editor-toolbar {
  background-color: #f8f9fa;
  border: 1px solid #e1e8ed;
  border-bottom: none;
  padding: 8px 12px;
  border-radius: 4px 4px 0 0;
}

.toolbar-btn {
  background: none;
  border: none;
  font-size: 16px;
  padding: 6px 10px;
  margin-right: 8px;
  cursor: pointer;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.toolbar-btn:hover {
  background-color: #e9ecef;
}

#answer-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e1e8ed;
  border-radius: 0 0 4px 4px;
  font-size: 16px;
  font-family: inherit;
  resize: vertical;
  box-sizing: border-box;
}

#answer-input:focus {
  outline: none;
  border-color: #1a8917; /* Quora's signature green accent */
  box-shadow: 0 0 0 3px rgba(26, 137, 23, 0.1);
}
4. Extra Notes
  • If you want a "what you see is what you get" (WYSIWYG) experience instead of Markdown syntax, you could replace the textarea with a contenteditable div and use document.execCommand() for formatting. But using a textarea with Markdown is simpler for backend storage and rendering.
  • For better user experience, you could replace the prompt() calls with a custom modal (built with HTML/CSS/jQuery) instead of browser default prompts.

内容的提问来源于stack exchange,提问作者vidhey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:29:44